javascript NodeJS Multer 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29490833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NodeJS Multer is not working
提问by DingGGu
I tried to file upload with NodeJS + ExpressJS + Multer but does not work well.
我尝试使用 NodeJS + ExpressJS + Multer 上传文件,但效果不佳。
My ExpressJS Version is 4.12.3
我的 ExpressJS 版本是 4.12.3
this is my source
这是我的来源
server.js:
服务器.js:
var express = require('express'),
multer = require('multer');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(multer({ dest: './uploads/'}));
app.post('/', function(req, res){
console.log(req.body); // form fields
console.log(req.files); // form files
res.status(204).end()
});
app.get('/', function(req, res) {
res.sendFile('public/index.html');
});
app.listen(5000, function() {
console.log("start 5000");
});
public/index.html:
公共/index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input id="file" type="file"/>
<button type="submit">test</button>
</form>
</body>
</html>
My NodeJS Console Log when I click Submit Button:
单击提交按钮时,我的 NodeJS 控制台日志:
"C:\Program Files\nodejs\node.exe" server.js
start 5000
{}
on NodeJS Console, there is empty object at req.files Is some problem on my source?
在 NodeJS 控制台上,req.files 中有空对象 我的源有问题吗?
回答by NarendraSoni
I don't see you calling any API to upload file on click of submit button. Let me give you more comprehensive implementation.
我没有看到您在单击提交按钮时调用任何 API 来上传文件。让我给你更全面的实现。
multer config in app.js
multer 配置 app.js
app.use(multer({
dest: './uploads/',
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
},
onFileUploadStart: function (file) {
console.log(file.fieldname + ' is starting ...')
},
onFileUploadData: function (file, data) {
console.log(data.length + ' of ' + file.fieldname + ' arrived')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
}
}));
View
看法
<form id="uploadProfilePicForm" enctype="multipart/form-data" action="/user/profile_pic_upload" method="post">
<input type="file" multiple="multiple" id="userPhotoInput" name="userPhoto" accept="image/*" />
<input type="submit" name="submit" value="Upload">
</form>
End point '/user/profile_pic_upload
' POST calls uploadProfilePic
in controller
控制器中的端点 ' /user/profile_pic_upload
' POST 调用uploadProfilePic
var control = require('../controllers/controller');
app.post('/user/profile_pic_upload',control.uploadProfilePic);
Upload profile pic logic in users controller
在用户控制器中上传配置文件图片逻辑
uploadProfilePic = function(req,res){
// get the temporary location of the file
var tmp_path = req.files.userPhoto.path;
// set where the file should actually exists
var target_path = '/Users/narendra/Documents/Workspaces/NodeExpressWorkspace/MongoExpressUploads/profile_pic/' + req.files.userPhoto.name;
// move the file from the temporary location to the intended location
fs.rename(tmp_path, target_path, function(err) {
if (err) throw err;
// delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
fs.unlink(tmp_path, function() {
if (err) {
throw err;
}else{
var profile_pic = req.files.userPhoto.name;
//use profile_pic to do other stuffs like update DB or write rendering logic here.
};
});
});
};
回答by Muhammad Usman Ali Baloch
Use this example, it uses firebase cloud function and firebase storage to upload file but you can use it for anything , it uses express-multipart-file-parser and works like charm the above link just works perfectly,I tested this code and pushed it to repo for you guys.Just add your configuration and there you go.
使用这个例子,它使用 firebase 云功能和 firebase 存储来上传文件,但你可以将它用于任何事情,它使用 express-multipart-file-parser 并且像魅力一样工作 上面的链接完美地工作,我测试了这段代码并推送了它为你们回购。只需添加您的配置即可。
回答by Bikesh M
Try this
试试这个
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (request, file, callback) {
callback(null, './uploads/');
},
filename: function (request, file, callback) {
console.log(file);
callback(null, file.originalname)
}
});
var upload = multer({ storage: storage });
app.post('/', upload.single('photo'), function (req, res) {
console.log(req.body) // form fields
console.log(req.file) // form files
res.status(204).end()
});
ref: http://wiki.workassis.com/nodejs-express-get-post-multipart-request-handling-example/
参考:http: //wiki.workassis.com/nodejs-express-get-post-multipart-request-handling-example/