本文介绍了如何使用JS fetch API发布表单数据并上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JS fetch API发布表单数据,我也成功发送了数据并获得了响应,但是上传的文件出现错误,我的文件没有上传,也没有将文件名存储到数据库中.

I am trying to post form data using JS fetch API, also i successfully send data and get response , but got an error in file uploaded my file is not uploaded , and also not get stored filename into database.

<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代码

And javascript code

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().还要检查拼写,您编写了与 formData 不同的 formdata .

No need to transform to JSON, and no need to use entries() on FormData. Also check the spelling, you wrote formdata which is different than formData.

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
});

这篇关于如何使用JS fetch API发布表单数据并上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:34