本文共 769 字,大约阅读时间需要 2 分钟。
后端提供接口,直接返回一个文件,基本的请求方式如下
axios({ url, method: 'POST', params, data, headers: { 'ContentType': 'application/octet-stream;charset=uft-8;' }, responseType: 'blob' })
具体地说明一下
method
,可以是post、getparams
, 链接里的参数,根据接口需要来加入data
, 请求body里的参数,根据接口需要来写headers
, 请求的header,根据接口需要来写,octet-stream是未指定具体类型的streamresponseType:'blob'
这个很重要,需要明确指定接口返回的类型。这样才能基于blob进行后续处理response.headers[content-disposition]
一般接口返回时,会在返回的请求头上加上这个,在这里,会有文件名信息。拿到请求返回的blob后,下载文件的代码实现
fileReader
实现const reader = new FileReader() reader.readAsDataURL(res.data) reader.onload = function(e) { DownFileByUrl(e.target.result, decodeURIComponent(res.fileName))}
URL.createObjectUrl
方式const URL = window.URL || window.webkitURL const url = URL.createObjectURL(blob)DownloadFileByUrl(url)
转载地址:http://muxwn.baihongyu.com/