【问题标题】:FormData image is undefined in post request with FetchFormData 图像在使用 Fetch 的发布请求中未定义
【发布时间】: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


【解决方案1】:

它是未定义的,因为您没有用于处理多部分/表单数据的中间件,用于上传文件。您可以使用multer 访问req.file 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 2021-09-01
    • 2017-01-26
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多