简体   繁体   English

Sails.js - 文件上传

[英]Sails.js - file upload

I am working on a Sails.js project at the moment and I would like to upload a file to the server and save the link to that file in my database.我目前正在处理一个 Sails.js 项目,我想将一个文件上传到服务器并将指向该文件的链接保存在我的数据库中。

For example, when I click add FILE, it should allow me to select a file from my computer and when I click submit, it should upload the file to the URL that I point ( create the folder if it does not exist).例如,当我单击添加文件时,它应该允许我从我的计算机向 select 发送一个文件,当我单击提交时,它应该将文件上传到我指向的 URL(如果不存在则创建文件夹)。

Can this be accomplished with Sails.js?这可以用 Sails.js 完成吗? If yes, how?如果是,如何?

Thank you!谢谢你!

This will get you most of the way there: https://github.com/balderdashy/sails/issues/27 这将让你大部分时间到那里: https//github.com/balderdashy/sails/issues/27

You can use https://github.com/aconbere/node-file-utils to create directories, etc. Install it with 您可以使用https://github.com/aconbere/node-file-utils创建目录等。安装它

npm install file

Require file in the module having code similar to that in .../sails/issue/27. 要求模块中的文件具有类似于... / sails / issue / 27中的代码。

This blog has has a good example of handling a file upload--it worked for me: 这个博客有一个处理文件上传的好例子 - 它对我有用:

http://maangalabs.com/blog/2014/08/12/uploading-a-file-in-sails/ http://maangalabs.com/blog/2014/08/12/uploading-a-file-in-sails/

upload: function  (req, res) {

    // Call to /upload via GET is error
    if(req.method === 'GET')
          return res.json({'status':'GET not allowed'});                        

    var uploadFile = req.file('uploadFile');
    console.log(uploadFile);

    uploadFile.upload(function onUploadComplete(err, files) {

        // Files will be uploaded to .tmp/uploads

        // IF ERROR Return and send 500 error with error
        if (err) return res.serverError(err);                               

        console.log(files);
        res.json({status:200,file:files});
    });
}

The best option is to do this on middleware最好的选择是在中间件上执行此操作

aware to check filetypes and route matching otherwise bad actors can upload malicious files知道检查文件类型和路由匹配,否则不良行为者可以上传恶意文件

Edit config/http.js like this像这样编辑 config/http.js

serverOptions: {
    timeout: 600000,
  },
  middleware: {

    /***************************************************************************
    *                                                                          *
    * The order in which middleware should be run for HTTP requests.           *
    * (This Sails app's routes are handled by the "router" middleware below.)  *
    *                                                                          *
    ***************************************************************************/

    order: [
      'cookieParser',
      'session',
      'bodyParser',
      'fileUpload', //new middleware
      'compress',
      'poweredBy',
      'router',
      'www',
      'favicon',
    ],

fileUpload middleware code文件上传中间件代码

fileUpload: (function () {
  return function (req, res, next) {
    console.log('Received HTTP request: ' + req.method + ' ' + req.path);
    const uploadRoutes = ['/save-user-profile-image'];
    if (req.method === 'POST' && uploadRoutes.includes(req.path)) {


      req.file('profileImage').upload(
        {
          maxBytes: 10000000,
          dirname: require('path').resolve(sails.config.appPath, 'uploads/'),
          saveAs: `YOUR_FILE_NAME.jpg`
        },
        function (err, files) {
          if (err) {
            console.log('Error: ' + err.message);
            return next(err);
          }

          if (files.length > 0) {
            var uploadedFile = files[0];
            var fileName = uploadedFile.filename;
            var sizeInBytes = uploadedFile.size;
            var path = uploadedFile.fd;

            
         
            req.body.fileName = fileName;
            req.body.sizeInBytes = sizeInBytes;
            req.body.filePath = path;
            req.body.imageName = name;
          
          }

          return next();
        }
      );
    } else {
      return next();
    }
  };
})(),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM