图像从浏览器上传到 node.js 服务器......图像没有到达那里......?"/>
尝试将图像从浏览器上传到 node.js 服务器......图像没有到达那里......?
浏览器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)
}
}
当我尝试记录 req.files 的内容时,我得到 *undefined *
我已经花了几个小时了。请帮助我
尝试了很多更改并通过谷歌搜索解决方案,但此时无法弄清楚问题所在。
需要帮助
回答如下:更多推荐
尝试将图像从浏览器上传到 node.js 服务器......图像没有到达那里......?
发布评论