Node.js和Multer-在回调函数(req,res)中处理上载文件的目标 [英] Node.js and Multer - Handle the destination of the uploaded file in callback function (req,res)

查看:137
本文介绍了Node.js和Multer-在回调函数(req,res)中处理上载文件的目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm a newbie in Node.js and i have run into a very simple problem lately.

我正在使用一个名为multer的模块,因此用户可以上传图像. 在我的Web应用程序中,所有用户都具有唯一的ID,我希望将上传的图像存储在基于其ID命名的目录中.

I'm using a module named multer, so users can upload images. In my web app all the users have a unique id, and i want the uploaded images to be stored in a directory named based on their id.

示例:

.public/uploads/3454367856437534

这是我的routes.js文件的一部分:

Here is a part of my routes.js file:

// 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生成正确的目录?

So i can use it with multer to generate the proper directory based on the id?

编辑,这是我尝试过但没有起作用的内容:

EDIT Here is what i have tried and didn't work:

module.exports = function(app, passport) {

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

}

推荐答案

更新

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

Quite a few things have changed since I posted the original answer.

使用multer 1.2.1.

  1. 您需要使用DiskStorage来指定 where & 操作方式.
  2. 默认情况下,multer将使用操作系统的默认目录.在我们的案例中,由于我们特别关注位置.在将文件保存到该文件夹​​之前,我们需要确保该文件夹存在.
  1. You need to use DiskStorage to specify where & how of the stored file.
  2. By default, multer will use the operating system's default directory. In our case, since we are particular about the location. We need to ensure that the folder exists before we could save the file over there.

注意:当提供目标功能时,您负责创建目录.

Note: You are responsible for creating the directory when providing destination as a function.

更多此处

'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

用于重命名放置上载文件的目录的功能.

Function to rename the directory in which to place uploaded files.

可从 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
});

这篇关于Node.js和Multer-在回调函数(req,res)中处理上载文件的目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆