javascript - 使用 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 });
}
}
解决方案
从标题中删除内容类型,因为内容类型不'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
});
}
};
推荐阅读
- c# - 放置在弹出窗口内时,第一次单击时不会触发按钮单击事件
- python - 此估算器不支持 Dask 数据帧
- c# - 如何使用 http 请求发送空 url 参数?
- java - 程序给出线程错误异常
- git - Git合并分支意外收到提交
- python - 当我们从模块中调用函数时,函数内部只有注释,那么函数究竟是如何实现其功能的呢?
- google-cloud-platform - 如何连接到 gcloud 实例并在启动时或在一行中连续运行命令
- python - PyQt5低于Qlabel空间宽度
- mysql - MySQL 使用 Group by 和 Order by
- .net-core - 将带有公钥的 .pem 加载到 x509Certificate2