我想将带有ajax的照片上传到Express,但每次我提交表单时都不会生成我在代码中的html,它只是重定向我并将图片数据显示为对象。甚至可以上传图片,如果成功,可以生成html所需的响应吗?
这是Express代码:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/basic_uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
});
const upload = multer({ storage: storage })
router.post('/ajax_upload', upload.single('ajaxFile'), (req, res) => {
let data = req.file;
res.status(200).json(data)
});
上传图片一切正常。
然后(Ajax):
$(document).ready(function (event){
$("#uploadForm").on('submit',( function (event) {
event.preventDefault();
$.ajax({
url: "/ajax_upload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: successHandler,
error: function(error){
$("#targetLayer").html(`<span>` + error + `</span>`)
}
});
}));
function successHandler(data) {
// let html = `<img src="/uploads/basic_uploads/` + data.filename + `" >`
// $("#targetLayer").html(html)
$("#targetLayer").html(`<p>AT LAAAAAST</p>`)
}
});
这里是html:
<div class="well">
<form id="uploadForm" action="/ajax_upload" method="POST" enctype="multipart/form-data" onsubmit="submitFormAjax();return false;">
<div class="form-group">
<label for="exampleInputFile">Ajax file Upload with Multer</label>
<input type="file" name="ajaxFile" id="exampleInputFile">
</div>
<input class="btn btn-primary" type="submit" value="Basic file Upload">
</form>
<div id="targetLayer"></div>
</div>
答案 0 :(得分:0)
在successHandler函数之后添加return false语句并重试,
$(document).ready(function (event){
$("#uploadForm").on('submit',( function (event) {
event.preventDefault();
$.ajax({
url: "/ajax_upload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: successHandler,
error: function(error){
$("#targetLayer").html(`<span>` + error + `</span>`)
}
});
}));
function successHandler(data) {
// let html = `<img src="/uploads/basic_uploads/` + data.filename + `" >`
// $("#targetLayer").html(html)
$("#targetLayer").html(`<p>AT LAAAAAST</p>`)
}
return false;
});