# 前言
因为业务要求,查了下怎么获取进度,但是资料很分散。虽然又被业务搁置了,还是记录下怎么实现的。
# 现有代码
# 前端 React
axios 向服务器端通信
async post<T>(url: string, body: any): Promise<T>{
return axios
.post(`${this.serverDomain}${url}`), JSON.stringify(body),{
headers: this.headers,
})
.then(
(axiosResponse)=>(
return axiosReponse.data as T;
),
(axiosError)=>(
return axiosError?.reponse?.data || axiosError;
),
);
}
service 层的相关方法
async download(ids: number[], locale: string):
Promise<ApiResponse<Blob>> {
const url = `${this.baseUrl}/download?locale=${locale}`;
return this.httpService.post<FileReponse>(url, [...ids]).then(
(response: any) => response,
(error) => error,
);
}
component 层调用
extractService.download(ids, intl.locale).then((response: ApiResponse<Blob>)=>{
//...
const linkSource = `data:application/vnd.openxmlformas-officedocument.spreadsheetml.sheet;base64,^${reponse.data}`;
const link = document.createElement(`a`);
link.href = linkSource;
link.download = 'extract.zip';
link.click();
//...
});
# 后端 Spring
//... | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
ZipOutputStream zos = new ZipOutputStream(baos); | |
... | |
final var fileByteArray = baos.toByteArray(); | |
... | |
final var fileResponseDto = new FileResponesDto(); | |
fileResponseDto.setData(fileByteArray); | |
return ResponseEntity.status(HttpStatus.SC_OK).body(fileResponseDto); |
# 解决过程
一开始找解决方案的时候很迷茫,因为一方面后端处理生成文件的时间在我的认知里是不可预估的,一方面怎么获取实时下载进度也是难以想象的。在寻找的过程中,发现进度条可能只是用来处理已生成好的文件,就像 chrome 下载时有绿色转动的小圈进度条。另一方面原以为是 react 本身也可以通过方法的内部获取实时下载好的文件大小,我还以为需要 webpack 之类服务器端实时发包的功能。
在边找边试的过程中,也遇到了不少坑。首先是大部分资料用的都是过时的 addEventListener,我还以为 react 也有,找了半天发现业务底层是 axios,可以直接在 parameter 加 onDownloadProgress。一些旁门左道试图使用 transfer-encoding: chunked,这样加了之后反而弄巧成拙更加复杂了。之后发现只要在后端加入 content-lengh 就能获取文件长度,这个属性在前端的 header 里面也以 total 形式出现。但是加了之后反而下载不了,因为 content-length 是整个数据包的大小,而并非是指单个 json 数据包大小,如果只是下载文件倒是没有问题,像业务这种需要 dto 传送其他信息的,就不能用,因为到达 length 之后 json 数据包直接就结束传递了,所以导致 json 的数据不完整。解决方法是使用自定的属性头比如 File-size,但是因为浏览器安全需要不允许非 expose 的 header 出现,所以浏览器会警告并停止获取 json。如何去使浏览器信任自己的设置的 header 呢?就需要在 response 响应里面提前说好,在 Access-Control-Expose-headers 里面加入我们自己的头。
另外使得浏览器不会显示自己的进度条,需要加入以下方法:
windows.URL.revokeObjectURL(linkSource);
example 代码实现:
async post<T>(url: string, body: any, onDownloadProgress: any): Promise<T>{
return axios
.post(`${this.serverDomain}${url}`), JSON.stringify(body),{
headers: this.headers,
onDownloadProgress: onDownloadProgress
})
.then(
(axiosResponse)=>(
return axiosReponse.data as T;
),
(axiosError)=>(
return axiosError?.reponse?.data || axiosError;
),
);
}
...
async download(ids: number[], locale: string, onDownloadProgress: (progressEvent: any) => void):
Promise<ApiResponse<Blob>> {
const url = `${this.baseUrl}/download?locale=${locale}`;
return this.httpService.post<FileReponse>(url, [...ids],onDownloadProgress).then(
(response: any) => response,
(error) => error,
);
}
...
const onDownloadProgress = (progressEvent: any) => {
let total = progressEvent.currentTarget.getResponseHeader('File-Size');
let percentCompleted = total ? Math.floor(progressEvent.loaded / total) * 100).toFixed(2) : 1
}
extractService.download(ids, intl.locale, onDownloadProgress).then((response: ApiResponse<Blob>)=>{
//...
const linkSource = `data:application/vnd.openxmlformas-officedocument.spreadsheetml.sheet;base64,^${reponse.data}`;
const link = document.createElement(`a`);
link.href = linkSource;
link.download = 'extract.zip';
link.click();
//...
window.URL.revokeObjectURL(linkSource);
});
//... | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
ZipOutputStream zos = new ZipOutputStream(baos); | |
... | |
final var fileByteArray = baos.toByteArray(); | |
... | |
final var fileResponseDto = new FileResponesDto(); | |
fileResponseDto.setData(fileByteArray); | |
return ResponseEntity.status(HttpStatus.SC_OK). | |
.header("Access-Control-Expose-Headers", "File-Size") | |
.header("File-Size", String.valueOf(fileByteArray.length)) | |
.body(fileResponseDto); |