6

任何人都知道为什么“重命名”功能(以及所有其他 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)

});
4

2 回答 2

9

似乎随着时间的推移,用法已经发生了变化。目前,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 表单发布的情况下,表单上传元素输入名称。

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

您也可能对限制 ( https://www.npmjs.com/package/multer#limits ) 和文件过滤器 ( https://www.npmjs.com/package/multer#filefilter )感兴趣

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

于 2015-08-28T14:47:47.297 回答
0

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

于 2020-09-28T23:30:16.287 回答