multer回调不起作用?

时间:2015-08-17 07:36:49

标签: uploading multer

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

});

2 个答案:

答案 0 :(得分:8)

似乎用法随着时间的推移而改变。目前,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

答案 1 :(得分:0)

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