一、请求
1、点击按钮下载文件,请求后端接口,后端返回文件流,前端通常会设置响应类型为 responseType: ‘blob’。
但是response.data是一个Blob格式的数据,和正常的格式已经不同了,后端返回的message也获取不到。
!
2、正常数据格式返回的数据。
我们很明显的看到data的数据不一样。
二、点击按钮请求失败,下载后端返回的失败文件,请求成功则提示后端成功信息
// 我的需求是,点击上传文件按钮,上传文件成功则提示成功信息,上传文件失败则自动下载上传失败的文件。请根据自己的需求来实现
this.$http({
url: this.$http.adornUrl('/ability/import'),
method: 'post',
responseType: 'blob', // 类型必须为blob
headers: {
'Content-Type': 'multipart/form-data', // 我这是上传的文件需要定义的请求头类型
},
data: form, // 文件
}).then((response) => { // response响应体
if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') { // 判断response.request.responseType是否存在blob或arraybuffer
if (response.data.type === 'application/json') {
//FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。其中File对象可以是来自用户在一个元素上选择文件后返回的FileList对象,也可以来自拖放操作生成的 DataTransfer对象,还可以是来自在一个HTMLCanvasElement上执行mozGetAsFile()方法后返回结果。
const reader = new FileReader() // 通过构造函数初始化一个FileReader对象
// FileReader.onload事件在读取完成后触发
reader.onload = () => {
// TODO 错误处理
// 将reader.resul转成json对象
if(JSON.parse(reader.result).resultCode == '00000'){
this.dialogLoading = false
this.fileList = []
this.showMultipleUp = false
this.getDataList()
this.$message.success(JSON.parse(reader.result).resultMsg)
}else{
this.dialogLoading = false
this.$message.error(JSON.parse(reader.result).resultMsg)
}
}
reader.readAsText(response.data)
return null
} else {
this.$message.error('上传失败,失败文件正在下载中...')
this.dialogLoading = false
this.fileList = []
this.showMultipleUp = false
// 拿到响应头中content-disposition并处理,拿到后端返回的文件名
const contentDisposition = response.headers['content-disposition'];
const fileName = decodeURIComponent(contentDisposition.substring(contentDisposition.indexOf('=') + 1));
let blob = new Blob([response.data], {type: "application/vnd.ms-excel"});
const blobUrl = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.download = fileName
a.href = blobUrl
a.click()
}
}
})
三、下课