首页 > 解决方案 > 使用 fetch POST 方法将文件发送到服务器 API

问题描述

我正在尝试将 .xml 文件从我的 PC 发送到服务器,但我收到此错误: POST https://localhost:44391/api/edit net::ERR_ABORTED 415

文件状态

const [file, setFile] = useState();

输入和按钮

 <input type="file" id="file" onChange={(e) => setFile(e.target.files[0])} />
 <button onClick={send}>DASD</button>

点击功能

const send = async () => {
        if (file) {
            let formData = new FormData();
            formData.append('file', file);
            console.log(formData);
            await fetch("https://localhost:44391/api/edit", 
            { method: "POST", body: formData });
        }
    }

标签: javascriptreactjsfetch

解决方案


从标题中删除内容类型,因为内容类型不'text/xml应该是multipart/form-data.

Fetch api会根据内容自动添加header。这将是什么Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

const send = async () => {
  if (file) {
    let formData = new FormData();
    formData.append("file", file);
    console.log(formData);
    await fetch("https://localhost:44391/api/edit", {
      method: "POST",
      body: formData
    });
  }
};


推荐阅读