Jquery 带环回的文件上传

Jquery 带环回的文件上传,jquery,node.js,file-upload,loopbackjs,google-api-nodejs-client,Jquery,Node.js,File Upload,Loopbackjs,Google Api Nodejs Client,我用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 f

我用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!');
            }
        });
    }

});
安装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,因此接下来-

还可以使用其他此类指令

注意-根据您的评论-
实际上,我们的问题是,我们需要从客户端上传一个文件并将该文件存储在数据库中,但在保存到DB之前,我们需要在服务器端获取文件,如果我们通过Post API在服务器端获取文件,那么我们就可以轻松地将文件存储到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);
        });
    };
};

您可以使用环回的默认设置上载文件/图像。转到并按照说明进行操作,特别是查看示例项目是如何实现文件上载的

为此,您必须创建一个数据源和一个容器模型

创建数据源:

$ 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
  • 基类:模型
  • 通过REST API公开审阅者?
  • 自定义复数形式(用于构建REST URL):是

这对我来说很有效,我使用了LoopbackJs

顺便说一下,环回框架是基于ExpressJs的

您可以将此回答视为“和”强>版本< <强> > 安装插件依赖性:

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 framework BTW):

下载并放入/client/test文件上载网页:

运行node.app并指向 您应该能够上载文件,并在“网络”选项卡中找到上载的文件名响应:


您是否检查了环回存储组件-是的,但我们如何使用它!!请澄清谢谢,我们需要将文件存储在服务器端,而不是容器中。检查链接,它有实现它的步骤,还有链接到示例-容器只是服务器端的文件夹,将给出另一个选项作为答案,因为它不适合于注释框request POST/api/fileupload/upload的unhandled error:error:发送后无法设置标题。在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:356:11)中,我认为它在这里生成错误-res.json(uploadedFileName);您能在附近控制台
文件
变量吗,//文件将在
文件
变量中访问,并检查您是否得到任何控制,因此它不打印任何内容,我正在输入代码,请检查是否缺少某些内容。@Aks1357工作正常。但是res.end(result)没有显示任何数据。控件没有打印-console.log(“------------Second Rakesh-->”);添加
var fs=require('fs')
multer
之后,因为我们也在使用它,所以它没有在代码中声明,而是被使用,这产生了错误非常感谢,你看到我的代码了吗?你的意思是,在var multer=require('multer')之后;我们需要添加var fs=require('fs');谢谢,但是它显示了错误-请求POST/api/fileupload/upload的未处理错误:错误:发送后无法设置头。当我在控制台中打印'storage'时,它会显示-DiskStorage{getFilename:[Function:filename],getDestination:[Function:destination]}
npm install jquery-file-upload-middleware
 //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' }))
...
    "files": {
  "loopback#static": {
    "params": "$!../client" 
  }
}
...