【发布时间】:2020-09-01 01:46:26
【问题描述】:
我正在使用个人资料图片文件上传系统,我的 HTML:
<form enctype="multipart/form-data" id="imageUpload" >
<img id="profileImage" src="./images/avatar.png">
<button type="button">
<input type="file" name="image" id="inpFile" class="hidden" onchange="uploadPicture(this)">
<label for="inpFile">Download</label></button>
我的脚本:
async function uploadPicture(input) {
//show user the image
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#profileImage').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
const form = document.querySelector('#imageUpload')//tried to send form.image.value before
const formData = new FormData();
formData.append("inpFile", input.files[0]);
try {
const res = await fetch('/my-profile-image-upload', {
method: 'POST',
body: JSON.stringify(Object.fromEntries(formData)),
headers: {
'Content-Type': 'application/json'
}
})
} catch (error)
console.log(error);
}
所以我在一个对象中发送这个文件,但在我的控制器中
module.exports.upload_picture = (req, res) => {
const { FormData } = req.body;
console.log(FormData);
}
我越来越不确定。 我的目标是将此图像存储在我的公用文件夹中,因为它对所有用户可见并将文件名存储在数据库中,但我无法使用 fetch 发送此文件。我确实有
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
在我的 app.js 文件中
关于如何使用 fetch 发送此图像的任何想法?
【问题讨论】:
-
您不能对 FormData 对象进行字符串化,它必须使用它应该自行设置的多部分内容类型标头
标签: javascript node.js file express fetch