重点:multipart/form-data 后端识别上传类型必填
1. form 表单上传
<!-- enctype="multipart/form-data" 这个必填 -->
<form
action="http://127.0.0.1:8080/users/avatar"
method="post"
enctype="multipart/form-data"
>
<input name="name" type="text" />
<input id="file" name="files" type="file" />
<button>提交</button>
</form>
<script>
const upload = document.getElementById("file");
upload.onchange = function (value) {
const fileList = value.target.files;
console.log(fileList);
};
</script>
2. js 上传
// 后端上传接口
function updateAvatar(data) {
return api({
url: "/users/avatar",
method: "post",
// 设置请求头(重点)
headers: {
"Content-Type": "multipart/form-data",
},
data,
});
}
let cutDown = (data) => {
// 构建 form 表单;
let formData = new FormData();
let { file } = data;
console.log(data);
// file 参数命名和后端一致
formData.append("file", file);
updateAvatar(formData).then((res) => {
console.log(res);
});
};