[js进阶]axios+FormData文件上传
原理:FormData上传
创建一个FormData对象,将得到的文件流对象放在FormData内,然后使用axios上传
请求头设置
Content-Type(内容类型),一般是指网页中存在的 Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,这就是经常看到一些 PHP 网页点击的结果却是下载一个文件或一张图片的原因。
Content-Type 标头告诉客户端实际返回的内容的内容类型。
语法格式:
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=something
以application开头的媒体格式类型:
-
application/xhtml+xml :XHTML格式 -
application/xml:XML数据格式 -
application/atom+xml :Atom XML聚合格式 -
application/json:JSON数据格式 -
application/pdf:pdf格式 -
application/msword :Word文档格式 -
application/octet-stream :二进制流数据(如常见的文件下载) -
application/x-www-form-urlencoded : <form encType="">
中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
另外一种常见的媒体格式是上传文件之时使用的:
-
multipart/form-data :需要在表单中进行文件上传时,就需要使用该格式
headers: { 'Content-Type': 'multipart/form-data' }
请求上传文件方法
export function submitTask(parameter) {
return request({
url: 'xxx',
method: 'post',
data: parameter,
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
上传函数中操作FormData对象
无论是用input type=“file”还是一些框架的上传组件,都可以的到一个file文件流,示例使用的是antd的Upload组件。
<a-upload-dragger
:fileList='fileList'
accept='.zip'
:beforeUpload='beforeUpload'
:remove='handleRemove'
>
export default {
data() {
return {
fileList: [],
uploading: false,
};
},
methods: {
handleRemove(file) {
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
},
beforeUpload(file) {
this.fileList = [...this.fileList, file];
return false;
},
handleUpload() {
const { fileList } = this;
const formData = new FormData();
fileList.forEach(file => {
formData.append('files[]', file);
});
this.uploading = true;
// You can use any AJAX library you like
reqwest({
url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
method: 'post',
processData: false,
data: formData,
success: () => {
this.fileList = [];
this.uploading = false;
this.$message.success('upload successfully.');
},
error: () => {
this.uploading = false;
this.$message.error('upload failed.');
},
});
},
}
}
最后上传的结果
原文始发于微信公众号(豆子前端):[js进阶]axios+FormData文件上传
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/56453.html