繁体   English   中英

如何使用 JS fetch API 发布表单数据和上传文件

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

我正在尝试使用 JS fetch 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);

无需转换为 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
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM