问题描述
正如问题标题所述,我需要根据文件扩展名过滤上传的文件.因此,我浏览了官方文档并搜索了该网站.
As question title explains, I need to filter uploaded files on the basis of file extension. So, I went through the official docs and searched this website.
我尝试过的事情
我尝试了遇到的解决方案.文件已成功上传,但问题是如何过滤文件.目前,我的Router.js文件如下所示.
I've tried solutions I came across. Files are being successfully uploaded, but the problem is how to filter files. Currently my Router.js file looks like this.
Router.JS
Router.JS
var multer = require('multer');
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
limits:{
files: 1,
fileSize: 1024 * 1024
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
},
onFileUploadStart: function(file) {
console.log("Inside uploads");
if (file.mimetype == 'image/jpg' || file.mimetype == 'image/jpeg' || file.mimetype == 'image/png') {
return true;
}
else
{
return false;
}
}
});
var upload = multer({ //multer settings
storage: storage
}).single('profilepic');
router.post('/profile', function(req, res){
upload(req,res,function(err){
if(err)
{
console.log(err);
}
else
{
console.log("Image was uploaded");
}
});
});
我尝试在onFileUploadStart
中回显某些内容,以检查它是否正在进入该功能.事实并非如此.除了onFileUploadStart
之外,我还尝试过fileFilter
,如该链接所述.没有帮助.有什么建议如何解决这个问题?预先感谢.
I tried echoing something in onFileUploadStart
to check if it is going into that function or not. And it was not. Besides onFileUploadStart
, I also tried fileFilter
as mentioned at this link, but it was not helpful. Any suggestions how to solve this? Thanks in advance.
推荐答案
使用multer
的示例:
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage,
fileFilter: function (req, file, callback) {
var ext = path.extname(file.originalname);
if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(new Error('Only images are allowed'))
}
callback(null, true)
},
limits:{
fileSize: 1024 * 1024
}
}).single('profilepic');
摘录自 Node.js-文件上传.原始作者是 Iceman 和米哈伊尔(Mikhail).归属详细信息可以在贡献者页面上找到.来源已获得 CC BY-SA 3.0 的许可,并且可以在文档存档.参考主题ID:4080,示例ID:14210.
Excerpted from Node.js - File upload. The original authors were Iceman and Mikhail. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 4080 and example ID: 14210.
这篇关于在Express JS中使用Multer基于扩展名过滤文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!