使用Loopback进行文件上传

Rak*_*esh 2 jquery loopback node.js google-api-nodejs-client loopbackjs

我创建了一个简单的文件上传应用程序环回.应用程序客户端我使用简单的html和Java Script代码.

我用ajax调用调用loopback api,这是Java脚本代码 -

$('#upload-input').on('change', function () {

    var files = $(this).get(0).files;

    if (files.length > 0) {
        // One or more files selected, process the file upload
        var form = new FormData();

        for (var index = 0; index < files.length; index++) {

            var file = files[index];
            form.append('Uploded Files', file, file.name);
        }

        $.ajax({
            url: 'api/fileupload/upload',
            type: 'POST',
            data: form,
            processData: false,
            contentType: false,
            success: function (data) {
                console.log('upload successful!');
            }
        });
    }

});
Run Code Online (Sandbox Code Playgroud)

但是我们没有在服务器端获取文件.在服务器端,我们创建了一个Loopback api.

可以帮助我们,如何使用loopback api上传文件.

这是我的loopback api代码 -

FileUpload.remoteMethod

(
        'upload', {
            http: {
                verb: 'post',
            },
            accepts:
            [
                { arg: 'ctx', type: 'object', http: { source: 'context' } },
                { arg: 'options', type: 'object', http: { source: 'query' } }

            ],
            returns: {
                arg: 'data',
                type: 'string',
                root: true
            }
        }
    );

    FileUpload.upload = function (context, options, callback) {
        //context.req.params = 'common';


    };
Run Code Online (Sandbox Code Playgroud)

小智 7

安装multer:https://github.com/expressjs/multer

npm install --save multer
Run Code Online (Sandbox Code Playgroud)

在MyModel.js中

var multer = require('multer');
var fs = require('fs');

module.exports = function (MyModel) {
    var uploadedFileName = '';
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            // checking and creating uploads folder where files will be uploaded
            var dirPath = 'client/uploads/'
            if (!fs.existsSync(dirPath)) {
                var dir = fs.mkdirSync(dirPath);
            }
            cb(null, dirPath + '/');
        },
        filename: function (req, file, cb) {
            // file will be accessible in `file` variable
            var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
            var fileName = Date.now() + ext;
            uploadedFileName = fileName;
            cb(null, fileName);
        }
    });


    MyModel.upload = function (req, res, cb) {
        var upload = multer({
            storage: storage
        }).array('file', 12);
        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                res.json(err);
            } else {
                res.json(uploadedFileName);
            }
        });        
    };

    MyModel.remoteMethod('upload',   {
        accepts: [{
            arg: 'req',
            type: 'object',
            http: {
                source: 'req'
            }
        }, {
            arg: 'res',
            type: 'object',
            http: {
                source: 'res'
            }
        }],
        returns: {
             arg: 'result',
             type: 'string'
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

前端 - 我使用AngularJS,所以关注 - https://github.com/nervgh/angular-file-upload

还有其他此类指令可供使用

PS - 根据你的评论 - Actually Our Problem is that , we need to upload a File from Client Side and Store this File in Database , But Before save in DB , we need to get files on Server side , if we get Files on Server side via Post API than we can easily store file in DB

无法为您提供准确的解决方案,但使用上述方法文件将上传到您的/client/uploads文件夹中,一旦上传,您就可以控制如何处理文件,一旦完成所有内容,最终将其删除(可选)