多个回调不起作用?

multer callbacks not working ?

有人知道为什么 "rename" 函数(以及所有其他 multer 回调)不起作用吗?

var express = require('express');
var multer  = require('multer');

var app = express();

app.use(multer({
    dest: 'uploads/',
    rename: function (fieldname, filename) {
        return new Date().getTime();
    },
    onFileUploadStart: function (file) {
        console.log(file.name + ' is starting ...');
    },
    onFileUploadComplete: function (file, req, res) {
        console.log(file.name + ' uploading is ended ...');
        console.log("File name : "+ file.name +"\n"+ "FilePath: "+ file.path)
    },
    onError: function (error, next) {
        console.log("File uploading error: => "+error)
        next(error)
    },
    onFileSizeLimit: function (file) {
        console.log('Failed: ', file.originalname +" in path: "+file.path)
        fs.unlink(path.join(__dirname, '../tmpUploads/') + file.path) // delete the partially written file
    }
}).array('photos', 12));



app.listen(8080,function(){
    console.log("Working on port 8080");
});

app.get('/',function(req,res){
    res.sendFile(__dirname + "/index.html");
});


app.post('/photos/upload', function (req, res, next) {
    // req.files is array of `photos` files
    // req.body will contain the text fields, if there were any
    //console.log(req.files);
    //console.log(req.body);
    res.json(req.files)

});

用法似乎随着时间的推移发生了变化。目前,multer 构造函数只接受以下选项 (https://www.npmjs.com/package/multer#multer-opts):

  • deststorage - 存储文件的位置
  • fileFilter - 控制接受哪些文件的函数
  • limits - 上传数据的限制

因此,例如重命名是通过配置适当的存储来解决的(https://www.npmjs.com/package/multer#storage)。

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads'); // Absolute path. Folder must exist, will not be created for you.
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
})

var upload = multer({ storage: storage });

app.post('/profile', upload.single('fieldname'), function (req, res, next) {
    // req.body contains the text fields 
});

fieldname 必须与请求正文中的字段名称匹配。即在HTML表单post的情况下,表单上传元素输入名称。

还可以查看其他中间件函数,例如 arrayfields - https://www.npmjs.com/package/multer#single-fieldname,它们提供了一些不同的功能。

您可能还对限制感兴趣 (https://www.npmjs.com/package/multer#limits) and file filter (https://www.npmjs.com/package/multer#filefilter)

而且 - 源是唯一的真实来源 - 看看吧!(https://github.com/expressjs/multer/blob/master/index.js)

这是一个 windows 问题。 windows 中不允许将日期作为 ISOString 用作文件名,并且违反了某些 CORS 策略。因此,有一个名为 uuid 的节点包可以完成这项工作。