带环回的文件上传

File Upload With Loopback

我用 loopbackjs 创建了一个简单的文件上传应用程序。 在应用程序的客户端,我使用了简单的 HTML 和 Javascript 代码,通过 AJAX 调用来调用环回 api:

$('#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!');
            }
        });
    }

});

我们没有在服务器端获取文件。在服务器端我们创建了一个 Loopback API,但是我们如何使用这个 API 上传文件?

这是我的环回 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';

    };

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

npm install --save multer

在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'
        }
    });
};

前端 - 我使用 AngularJS,因此请遵循 -https://github.com/nervgh/angular-file-upload

还有其他这样的指令可以使用

P.S。 - 根据您的评论 - 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 文件夹中,上传后您可以控制如何处理文件,一旦完成所有操作,最终删除它(可选)

请检查此代码:

module.exports = function (FileUpload) {
var multer = require('multer');

    FileUpload.remoteMethod(
        'upload', {
            http: {
                verb: 'post',
            },
            accepts:
            [{
                arg: 'req',
                type: 'object',
                http: {
                    source: 'req'
                }
            }, {
                arg: 'res',
                type: 'object',
                http: {
                    source: 'res'
                }
            }],
            returns: {
                arg: 'data',
                type: 'string',
                root: true
            }
        }
    );

    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
            console.log("----------Second Rakesh---");
            console.log(file);
            var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
            var fileName = Date.now() + ext;
            uploadedFileName = fileName;
            cb(null, fileName);
        }
    });

    FileUpload.upload = function (req, res, callback) {

        var upload = multer({
            storage: storage
        }).array('file', 12);

        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                res.json(err);
            }
            console.log("-------------Rakesh"); // Its Printing Rakesh

            res.json(uploadedFileName);
        });
    };
};

可以使用loopback默认的storage component. Go to the doc link上传files/Images,按照说明操作,具体看示例工程是如何实现文件上传的。

您必须为此目的创建数据源和容器模型。

创建数据源:

$ lb datasource
[?] Enter the data-source name: myfilesystem
[?] Select the connector for myfilesystem: other
[?] Enter the connector name: loopback-component-storage
[?] Install storage (Y/n)

创建容器模型:

  • 模型名称:容器
  • 数据源: myfilesystem
  • 基地class:型号
  • 通过 REST 公开 Reviewer API?
  • 自定义复数形式(用于构建 REST URL):是

这对我有用 LoopbackJs

Loopback 框架是顺便说一下基于ExpressJs

您可以将此答案视为 LoopbackJs https://github.com/blueimp/jQuery-File-Upload/ 的改编版本

安装插件依赖:

npm install jquery-file-upload-middleware

将此代码段添加到您的 /server/server.js :

 //Load Jquery File Upload handler
      var upload = require('jquery-file-upload-middleware'),
        bodyParser = require('body-parser');

        // configure upload middleware
        upload.configure({
            uploadDir: __dirname + '/public/uploads',
            uploadUrl: '/uploads',
            imageVersions: {
                thumbnail: {
                    width: 80,
                    height: 80
                }
            }
        });



        app.use('/upload', upload.fileHandler());
        app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

使用以下代码段修改 middleware.js,这样您的应用程序就可以 在 /client 文件夹中提供静态 HTML 资源 (顺便说一句,此文件属于 LoopbackJs 框架):

...
    "files": {
  "loopback#static": {
    "params": "$!../client" 
  }
}
...

下载并放置在/client/test文件上传网页: File Upload Webpage

运行 你的 node.app 并指向 http://localhost:3000/files/ 您应该能够上传文件并在“网络”选项卡中找到上传的文件名响应: