我如何 post 使用 JS fetch API 形成数据并上传文件

how do I post form data and upload file with the JS fetch API

我正在尝试 post 使用 JS 获取表单数据 API,我也成功发送数据并获得响应,但在上传文件时出错我的文件没有上传,也没有将存储的文件名存入数据库。

<form id="signup">
    <label for="myName">Send me your name:</label>
    <input type="text" id="myName" name="name" value="abc">
    <br>
    <label for="userId">your id:</label>
    <input type="text" id="userId" name="id" value="123">
    <br>
    <label for="pic">your photo:</label>
    <input id="profile" name="profile" id="profile" type="file">
    <br>
    <input id="postSubmit" type="submit" value="Send Me!">
</form>

和javascript代码

const thisForm = document.getElementById('signup');
    const profile = document.getElementById('profile');
    thisForm.addEventListener('submit', async function (e) {
    e.preventDefault();
    const formData = new FormData(thisForm).entries()
    formdata.append("profile",profile.files[0]);
        const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
            method: 'POST',
            headers: { 'Content-Type': 'multipart/form-data' },
            body: JSON.stringify(Object.fromEntries(formData))
        });

        const result = await response.json();
        console.log(result);

对于文件上传,您需要内容类型multipart/form-data。或者直接省略 Content-type,因为您的浏览器可能会自动设置它。

无需转换为JSON,也无需在FormData 上使用entries()。还要检查拼写,您写的 formdataformData.

不同
const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
  method: 'POST',
  headers: { 'Content-Type': 'multipart/form-data' },
  body: formData
});