浏览器Javascript:
const uploadFile = (file) => {
// add the file to the FormData object
const fd = new FormData();
fd.append("avatar", file);
// send `POST` request
fetch("http://localhost:3001/uploadtoazure", {
method: "POST",
body: fd,
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch((err) => console.error(err));
};
// select file input
const input = document.getElementById("upload");
// add event listener
input.addEventListener("change", () => {
uploadFile(input.files[0]);
});
服务器路由器处理程序:
async function uploadToAzure(req, res, next) {
try {
console.log(req.files);
if (!req.files) {
res.send({
status: false,
message: 'No file uploaded'
})
} else {
// Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
let avatar = req.files.avatar
// Use the mv() method to place the file in the upload directory (i.e. "uploads")
avatar.mv('./uploads/' + avatar.name)
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
})
}
} catch (err) {
res.status(500).send(err)
}
}
当我试图记录请求的内容时,我得到了 *undefined *。文件
我已经花了几个小时了。请帮帮我
尝试了很多变化和谷歌的解决方案,但不能找出什么是错误的,在这一点上。
需要帮助吗
1条答案
按热度按时间hmmo2u0o1#
使用express-fileupload中间件解决。谢谢你的帮助。