multer回调不起作用?

Ash*_*yad 6 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)

});
Run Code Online (Sandbox Code Playgroud)

tib*_*blu 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 
});
Run Code Online (Sandbox Code Playgroud)

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)