Fetch上传文件(不需要设置headers)
最近在项目中有一个上传文件的需求,然后我使用了fetch进行文件上传,
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试fetch上传文件</title>
</head>
<body>
<input type="file" id="files" onchange="upload(event)"/>
<script type="text/javascript">
function upload(event) {
const formData = new FormData();
formData.append('file', event.target.files[0]);
fetch('/upload', {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData,
}).then(response => response.json())
.then((data) => {
console.log(data);
});
}
</script>
</body>
</html>
运行结果:
code: 9999
data: []
msg: "文件不存在"
time: 1546948790.707762
我们查看一下Request Header
Content-Type: multipart/for