gpt4 book ai didi

uploading - multer 回调不起作用?

转载 作者:行者123 更新时间:2023-12-04 14:26:14 25 4
gpt4 key购买 nike

任何人都知道为什么“重命名”函数(以及所有其他 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 表单发布的情况下,表单上传元素输入名称。

    还可以查看其他中间件功能,例如 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 )

    关于uploading - multer 回调不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32045027/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com