我正在使用multer上传表单数据(一些图像文件)。
但是req.body和req.files都为空。当我上传图像时,收到成功消息“您的图像已上传”,但是我的文件夹为空。
我尝试了StackOverflow和GitHub上所有可用的解决方案。 但没有运气。
在我的代码下面
HTML文件中的表单
<form id="uploadForm" enctype="multipart/form-data" action="multerFile" method="post">
<input type="file" name="userPhoto" multiple />
<input type="submit" value="Upload Image" name="submit">
<input type='text' id='random' name='random'>
<br>
<span id="status"></span>
</form>
<script>
$(document).ready(function () {
$('#uploadForm').submit(function () {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function (xhr) {
status('Error: ' + xhr.status);
},
success: function (response) {
console.log(response)
$("#status").empty().text(response);
}
});
return false;
});
});
</script>
index.js
app.post('/multerFile', function (req, res) {
console.log("hi i am multer function")
var storage = multer.diskStorage({
destination: 'C:/Users/chandra/Documents/project/node_project/public'
});
var upload = multer({ storage: storage }).array('userPhoto', 2);
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.end("Error uploading file.");
} else {
console.log(req.body)
console.log(req.files);
req.files.forEach(function (f) {
console.log(f);
// and move file to final destination...
});
res.end("File has been uploaded");
}
});
});
我尝试过:
Express, Multer, BodyParser req.body empty array
multer req.body showing empty always
https://github.com/expressjs/multer/issues/351
https://github.com/expressjs/multer/issues/391
并且我遵循了本教程中关于multer
https://codeforgeek.com/2016/01/multiple-file-upload-node-js/
我无法理解我在做什么错?
请帮助。
预先感谢
答案 0 :(得分:0)
首先, .ajaxSubmit()不是jQuery的核心功能。您需要jQuery Form Plugin,但不知道是否按如下所示导入它:
<script src="http://malsup.github.com/jquery.form.js"></script>
最简单的方法是不用这样的插件来完成它:
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
type: 'POST',
url: '/multerFile',
data: formData,
success: function(response) {
console.log(response)
$("#status").empty().text(response);
},
contentType: false, // Prevent jQuery to set the content type
processData: false // Prevent jQuery to process the data
});
return false;
});
现在在后端,您的目的地应该是(在公共文件夹中上传文件夹):
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
});
答案 1 :(得分:0)
我刚刚将存储空间更改为
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: function(req, file, cb){
cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
一切正常。.