使用axios上传文件、下载(导出)文件

上传文件

上传文件需要将请求头的Content-Type设置为multipart/form-data

let file = e.target.files[0];           
 let data = new FormData(); //创建form对象
data.append('file',file);//通过append向form对象添加数据
data.append('chunk','0');

axios.post(
	"http://localhost:8081/api/peixun/vedio/uploadVideo",
	data,
	{ headers: { "Content-Type": "multipart/form-data" } }
).then(function (data) {
	console.log(data);
}, function (err) {
	console.log("err------: ");
	console.log(err);
})

下载(导出)文件

				axios({
					method: 'post',
					url: 'http://127.0.0.1/detail/list/export?mealcomeTime=1558691428000&rand=9848',
					responseType: 'blob',
					data: {"materialId":7079075,"beginDate":"2019-05-01 00:00:00","endDate":"2019-05-24 23:59:59","shipUnitId":4,"firstUnitId":4,"secondUnitId":4,"customerIds":[],"sortType":"","sortField":"","pageIndex":1,"pageSize":50},
					headers: {
						sessionId: 'c22824d846c94a459bf60cf286349399',
						sign: 'a29b3e56399e58d91459be2e64a8dbf9ecbfcd8097af08fb38ede3c64b15a889',
					}
				}).then(response => {
					let fileName = window.decodeURI(response.headers['content-disposition'].split('=')[1]);
					let link = document.createElement("a");
					link.href = window.URL.createObjectURL(new Blob([response.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"}));
					link.target = "_blank";
					link.download = fileName;
					document.body.appendChild(link); 
					link.click();
					document.body.removeChild(link);
				})

注意: responseTypeaxios的参数,不是在请求头里设置。之前在拦截器中加在请求头里,下载的文件乱码了

content-disposition

拿不到文件名?
需要后台响应头设置

"Access-Control-Expose-Headers":  "Content-Disposition"

意思让浏览器能访问这个响应头的Content-Disposition属性内容

相关文档

https://github.com/axios/axios/issues/895
I misunderstood the concept of CORS. Access-Control-Expose-Headers is a response header issued by the service.
This issue has nothing to do with axios.
The service should allow Content-Disposition header to be exposed for the client, in my case it does.
Due to HTTP access control CORS in browsers, the client application needs a proxy cors (in my case an express middleware) to read the header value.
Apologies for misunderstanding.

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值