admin管理员组文章数量:1401785
Working with expressjs for about a month by now I have stumbled across the problem of file uploads. Despite consulting Google & various blogs I have failed finding an answer to the following three questions:
What do I have to do / what settings for bodyParser do I have to choose in order to:
Make sure there was indeed a file uploaded (currently, when submitting the form without choosing a file an empty file gets created).
Where can I specify a value for the maxium size a file is allowed to have?
How can I omit the renaming of the file?
Currently I am including bodyParser in my express (v. 3.0.0) app with the following option:
{keepExtensions: true, uploadDir: __dirname + '/public/uploads'}
Working with expressjs for about a month by now I have stumbled across the problem of file uploads. Despite consulting Google & various blogs I have failed finding an answer to the following three questions:
What do I have to do / what settings for bodyParser do I have to choose in order to:
Make sure there was indeed a file uploaded (currently, when submitting the form without choosing a file an empty file gets created).
Where can I specify a value for the maxium size a file is allowed to have?
How can I omit the renaming of the file?
Currently I am including bodyParser in my express (v. 3.0.0) app with the following option:
{keepExtensions: true, uploadDir: __dirname + '/public/uploads'}
Share
Improve this question
asked Aug 3, 2012 at 15:45
R.G.R.G.
3913 silver badges10 bronze badges
2 Answers
Reset to default 4I recently ran into a similar problem. for Question #2, check http://www.senchalabs/connect/middleware-limit.html
app.use(express.limit('4M')); // in your app.configure()
app.post('/upload', function(req, res) {
var fs = require('fs'),
file = req.files.myfile; //your file field;
if(file.size === 0) { // question #1
fs.unlinkSync(file.path);
res.redirect('/error?');
} else { //question #3
var fn = file.path.split('/');
fs.rename(file.path, file.path.replace(fn[fn.length-1], file.name));
res.redirect('/success?');
}
});
About your concern
Make sure there was indeed a file uploaded (currently, when submitting the form without choosing a file an empty file gets created).
After long search I found a great solution
First you need to install node-formidable
Then after including the library, to check if file uploaded in the first place
var form = new formidable.IningForm();
form.parse(req, function(err, fields, files) {
if (Object.keys(files).length !== 0) {
console.log("File exists")
} else {
console.log("File does not exist")
}
});
And about the size you can check this.
form.maxFieldsSize = 2 * 1024 * 1024;
Best regards.
Abdulaziz Noor
本文标签:
版权声明:本文标题:javascript - expressjs file upload, check whether there was indeed a file sent, specify max filesize & keep its name - S 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744322701a2600580.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论