Node.js和Multer - 在回调函数中处理上传文件的目的地(req,res)

时间:2014-11-30 12:50:51

标签: javascript node.js variables upload multer

我是Node.js的新手,我最近遇到了一个非常简单的问题。

我正在使用名为multer的模块,因此用户可以上传图片。 在我的网络应用程序中,所有用户都有一个唯一的ID,我希望上传的图像存储在一个基于他们的id命名的目录中。

示例:

.public/uploads/3454367856437534

这是我的routes.js档案的一部分:

// load multer to handle image uploads
var multer  = require('multer');
var saveDir = multer({
  dest: './public/uploads/' + req.user._id, //error, we can not access this id from here
  onFileUploadStart: function (file) { 
  return utils.validateImage(file); //validates the image file type
  }
});

module.exports = function(app, passport) {

app.post('/', saveDir, function(req, res) {
                id     : req.user._id,  //here i can access the user id
    });
});

}

我如何访问

req.user._id 

以外的

function(req,res)

所以我可以使用multer根据id生成正确的目录吗?

编辑以下是我尝试过但没有用的内容:

module.exports = function(app, passport) {

app.post('/', function(req, res) {
    app.use(multer({
        dest: './public/uploads/' + req.user._id
    }));
});

}

3 个答案:

答案 0 :(得分:4)

<强>更新

自从我发布原始答案以来,有很多事情发生了变化。

multer 1.2.1

  1. 您需要使用DiskStorage指定 where &amp; 如何存储的文件。
  2. 默认情况下,multer将使用操作系统的默认目录。在我们的例子中,因为我们特别关注这个位置。在我们将文件保存到那里之前,我们需要确保该文件夹存在。
  3.   

    注意:在将目的地作为函数提供时,您负责创建目录。

    更多here

    'use strict';
    
    let multer = require('multer');
    let fs = require('fs-extra');
    
    let upload = multer({
      storage: multer.diskStorage({
        destination: (req, file, callback) => {
          let userId = req.user._id;
          let path = `./public/uploads//${userId}`;
          fs.mkdirsSync(path);
          callback(null, path);
        },
        filename: (req, file, callback) => {
          //originalname is the uploaded file's name with extn
          callback(null, file.originalname);
        }
      })
    });
    
    app.post('/', upload.single('file'), (req, res) => {
      res.status(200).send();
    });
    

    fs-extra用于创建目录just in case it doesn't exists

    原始回答

    您可以使用changeDest

      

    重命名放置上载文件的目录的功能。

    可从v0.1.8

    获取
    app.post('/', multer({
    dest: './public/uploads/',
    changeDest: function(dest, req, res) {
        var newDestination = dest + req.user._id;
        var stat = null;
        try {
            stat = fs.statSync(newDestination);
        } catch (err) {
            fs.mkdirSync(newDestination);
        }
        if (stat && !stat.isDirectory()) {
            throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
        }
        return newDestination
    }
    }), function(req, res) {
         //set your response
    });
    

答案 1 :(得分:0)

您只需参考输入名称即可解决此问题,并在分配之前重命名路径。

app.use(multer({ dest: './standard_folder/',
    rename: function (fieldname, filename) {

      var pathHelper ='';
      if(fieldname =='otherKindOfFolderNeeded'){
        pathHelper = '../../path/to/other/folder/';
      }
      return pathHelper+uuid.v4()+Date.now();
    },
    onFileUploadStart: function (file) {
      console.log(file.originalname + ' is starting ...')
    },
    onFileUploadComplete: function (file) {
      console.log(file.fieldname + ' uploaded to  ' + file.path)
      done=true;
    }
  })
);

答案 2 :(得分:0)

您可以使用multer来处理动态创建上传目录。在发送文件名之前,应调用输入参数(您要为其创建目录)。

var express = require('express');
var app = express();
var multer = require('multer');
var fs = require('fs');
var mkdirp = require('mkdirp');
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '5mb'}));
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true,
    limit: '5mb'
}));

var storage =   multer.diskStorage({
    destination: function (req, file, callback) {
        var Id = req.body.id;
        upload_path = "./"+Id;
        mkdirp(upload_path, function (err) {
            if (err) console.error(err)
            else {
                console.log('Directory created');
                //setting destination.
                callback(null, upload_path);
            }
        });

    },
    filename: function (req, file, callback) {
        callback(null, file.orginalname)
    }
});
//multer setting and getting paramaters.
var upload = multer({ storage : storage }).single('upload_file');

//creating request for upload file
app.post('/uploadFile', function(req, res){
    res.set({ 'content-type': 'application/json; charset=utf-8' });
    res.header("Content-Type", "application/json; charset=utf-8");
    res.header("Access-Control-Allow-Origin", "*");
    res.charset = 'utf-8';
    //function upload_process(){
    upload(req, res, function(err){
        if(err){
            console.log('Error-->');
            console.log(err);
            res.json({"status": "Failure", "message":'There was a problem uploading your files.'+err});
            return;
        }
        else{
            console.log("fieldname"+req.files.length);
            if( req.files.length != 0){
                res.json({"status" : "Success", "message":'Your files are uploaded.'});
                console.log('File uploaded!');
            }
            else{
                console.log("No file uploaded. Ensure file is uploaded.");
                res.json({"status" : "Failure", "message" : 'No file uploaded. Ensure file is uploaded.'});

            }
        }
    });

});

});

希望这有帮助!快乐的编码