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

dwthyt8l  于 2023-06-22  发布在  Node.js
关注(0)|答案(4)|浏览(113)

我是Node.js的新手,最近遇到了一个简单的问题。
我使用multer模块上传图片。在我的Web应用程序中,所有用户都有一个唯一的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
    });
});

}

如何访问回调function(req, res)之外的req.user._id属性,以便与multer一起使用,从而根据id生成正确的目录?

编辑以下是我尝试过但没有成功的:

module.exports = function(app, passport) {

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

}
h6my8fg2

h6my8fg21#

更新

自从我发布了最初的答案以来,很多事情都发生了变化。
关于multer 1.2.1
1.您需要使用DiskStorage来指定存储文件的 wherehow
1.默认情况下,multer将使用操作系统的默认目录。在我们的情况下,因为我们对位置很挑剔。我们需要确保文件夹存在,然后才能将文件保存到那里。
注意:当提供destination作为函数时,您负责创建目录。
更多

'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用于创建目录,以防目录不存在

原始答案

您可以使用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
});
2w3kk1z5

2w3kk1z52#

你可以解决这个问题,只要参考输入名称,并在分配之前重命名路径。

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;
    }
  })
);
uurity8g

uurity8g3#

你可以使用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.'});

            }
        }
    });

});

});

希望这有帮助!快乐编码

uhry853o

uhry853o4#

要从请求数据动态创建目录,只需将文件放在请求的末尾,将其他数据放在请求的顶部!multer将按照此顺序填充文本数据,并确保您可以访问用于动态目录创建的req数据。
enter image description here

相关问题