Подтвердить что ты не робот

Изменить изображение, полученное из loopback-component-storage

Я использую loopback для сохранения изображения в server.

Я хочу изменить имя файла файла, прежде чем получать его на сервере.

Также я хочу преобразовать его в другую форму эскиза, прежде чем сохранять.

Вот как я это делаю.

На стороне клиента

Upload.upload(
{
    url: '/api/containers/container_name/upload',
    file: file,
    fileName: "demoImage.jpg",
    //Additional data with file
    params:{
     orderId: 1, 
     customerId: 1
    }
});

На стороне сервера Я получаю запрос "params", но не получаю "Имя файла"

Имя моей модели хранения container

Container.beforeRemote('upload', function(ctx,  modelInstance, next) {

    //OUPTUTS: {orderId:1, customerId:1]}
    console.log(ctx.req.query);

    //Now I want to change the File Name of the file.
    //But not getting how to do that

    next();
})

Как изменить имя файла файла, сохраненного на сервере?

4b9b3361

Ответ 1

Я понял это.

Мы должны определить пользовательскую функцию getFileName в boot/configure-storage.js.

Предположим, что мой источник данных для loopback-component-storage presImage.

сервер/загрузки/Configure-storage.js

module.exports = function(app) {
    //Function for checking the file type..
    app.dataSources.presImage.connector.getFilename = function(file, req, res) {

        //First checking the file type..
        var pattern = /^image\/.+$/;
        var value = pattern.test(file.type);
        if(value ){
            var fileExtension = file.name.split('.').pop();
            var container = file.container;
            var time = new Date().getTime();
            var query = req.query;
            var customerId = query.customerId;
            var orderId    = query.orderId;

            //Now preparing the file name..
            //customerId_time_orderId.extension
            var NewFileName = '' + customerId + '_' + time + '_' + orderId + '.' + fileExtension; 

            //And the file name will be saved as defined..
            return NewFileName;
        }
        else{
            throw "FileTypeError: Only File of Image type is accepted.";
        }
    };
}

общая/модель/container.js

Теперь предположим, что моя модель контейнера container.

module.exports = function(Container) {
    Container.afterRemote('upload', function(ctx,  modelInstance, next) {
      var files = ctx.result.result.files.file;

      for(var i=0; i<files.length; i++){
        var ModifiedfileName = files[i].name;
        console.log(ModifiedfileName) //outputs the modified file name.
      } //for loop
      next();
    }); //afterRemote..
};

Теперь для преобразования изображений в размер эскиза

Загрузите quickthumb

Вот как использовать его с loopback.

Этот код скопирован непосредственно из миниатюp >

общая/модель/container.js

module.exports = function(Container) {

    var qt = require('quickthumb');

    Container.afterRemote('upload', function(ctx, res, next) {

        var file = res.result.files.file[0];
        var file_path = "./server/storage/" + file.container + "/" + file.name;
        var file_thumb_path = "./server/storage/" + file.container + "/thumb/" + file.name;

        qt.convert({
            src: file_path,
            dst: file_thumb_path,
            width: 100
        }, function (err, path) {

        });

        next();
    });

};

Ответ 2

В ответ на вышеприведенный ответ эта конфигурация-хранилище позволяет явно указывать имя файла через req.params.filename и по умолчанию использовать существующее имя, если оно не указано.

Configure-storage.js

module.exports = function(app) {

//Function for checking the file type..
    app.dataSources.storage.connector.getFilename = function(file, req, ignoreRes) {

        if (!req.params.filename) {
            return file.name
        }

        var fileExtension = file.name.split('.').pop()
        return req.params.filename + '.' + fileExtension

    };
}