我有一个包含文本字段和文件输入字段的表单。由于某些原因,所有数据都能够成功提交,但是文件却出现了问题。有人可以提供解决方法吗?谢谢。
index.ejs
<form enctype='multipart/form-data' onsubmit="create_ajax('/create_restaurant')">
<input type="file" id="restaurantProfilePicture" name="restaurantPicture" accept="images/*"><br>
前端JavaScript
function create_ajax(url) {
var formArray= $("form").serializeArray();
var data={};
for (index in formArray){
data[formArray[index].name]= formArray[index].value;
}
$.ajax({
url: url ,
data: data,
dataType: 'json',
type: 'POST',
success: function (dataR) {
console.log(dataR)
if (dataR.hasOwnProperty('message')){
document.getElementById('message').innerHTML = dataR.message;
}else{
window.location.replace('/restaurant?restaurantid=' + dataR.restaurant_ID);
}
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
}
});
event.preventDefault();
}
后端,route/index.js
var multer = require('multer');
var restaurantProfileName = "";
var storageRestaurantProfile = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/images/restaurant_profile_images')
},
filename: function (req, file, cb) {
// random token generation to avoid duplicated file name
var random_token = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 11; i++){
random_token += possible.charAt(Math.floor(Math.random() * possible.length));
}
restaurantProfileName = random_token + "-" + Date.now() + path.extname(file.originalname); // get file extension
cb(null, restaurantProfileName)
}
})
var restaurantProfileUpload = multer({ storage: storageRestaurantProfile });
router.post('/create_restaurant', restaurantProfileUpload.single("restaurantPicture"), function (req, res) {
enctype="multipart/form-data"
。请提供表单信息和最短的代码以便重现该问题。 - Kevin Peno