问题描述
前后端分离,文件下载后损坏
google、度娘了一大堆,大致手段都下面这些
https://www.cnblogs.com/sunsh...
https://blog.csdn.net/u010986...
https://blog.csdn.net/qq_3837...
https://github.com/axios/axio...
还是解决不了,只好来求助了
后端接口代码:
@ApiOperation(value="下载附件", notes="根据附件路径下载附件")
@GetMapping("/download")
public ResponseEntity<byte[]> download(String path) throws UnsupportedEncodingException{
if (fastDFSClient.getFileInfo(path) != null)
{
byte[] buffer = fastDFSClient.downloadFile(path);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename=" + FileUtil.getOriginalFilename(path));
headers.add("Content-Length", "" + buffer.length);
List<String> hlist = new ArrayList<String>();
hlist.add("Content-Disposition");
hlist.add("Content-Length");
headers.setAccessControlExposeHeaders(hlist);
return ResponseEntity.ok()
.headers(headers)
.contentLength(buffer.length)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(buffer);
}
return this.Resp423(null);
}
前端下载工具方法
import axios from 'axios';
import store from '../store';
import fileDownload from 'js-file-download'
export async function download(path) {
const res = await axios({
baseURL: process.env.BASE_API,
timeout: 2 * 60 * 60 * 1000,
headers:{'token':store.getters.token},
url:process.env.ServerName_COMMON+"/file/download",
method:"get",
params:{path:path},
responseType: "blob"
});
let disposition = res.headers['content-disposition'];
let filename = decodeURI(disposition.replace("attachment;filename=",""));
let fileType=res.headers['content-type'];
let resBlob = res.data;
let resData = null;
try {
let resText = await new Promise((resolve, reject) => {
// 通过 FileReader 接受并解析
let reader = new FileReader();
reader.addEventListener('abort', reject);
reader.addEventListener('error', reject);
reader.addEventListener('loadend', () => {
resolve(reader.result);
});
// 文件
reader.readAsText(resBlob);
});
resData = JSON.parse(resText);
} catch (err) {
}
if (resData) {
if (resData.error) {
} else {
}
} else {
fileDownload(resBlob, filename);
}
}
在具体组件中导入方法传入附件路径进行下载,结果下载下来后打不开。
难道是后端返回有问题?但是我把header中的token认证去掉后直接使用浏览器请求接口是能下载下来也能打开的。
另外在这里也找到个说法,说是二进制数据被转换成文本导致数据被破坏,难道还是axios用得不对?求指教
responseType: 'blob'要和params放在一个对象里,不要放到第3个参数