两种方式 都是可以直接触发浏览器下载并显示进度条的
前提是用 超链接的方式,不能用ajax
1,利用StreamingResponseBody + ResponseEntity
@GetMapping("/export1")
public ResponseEntity<StreamingResponseBody> exportData1() throws IOException {
File file = new File("D:\\Downloads\\Xshell-7.0.0164p.exe");
InputStream inputStream = Files.newInputStream(file.toPath());
StreamingResponseBody stream = outputStream -> {
int numberOfBytesToWrite;
byte[] data = new byte[64 * 1024];
while ((numberOfBytesToWrite = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, numberOfBytesToWrite);
}
inputStream.close();
};
String filename = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8);
// 处理空格 文件名里的空格会变成+号
filename = filename.replaceAll("\\+", "%20");
System.out.println("filename:"+filename);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(file.length())
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename + ";filename*=UTF_8''"+filename)
.body(stream);
}
2,FileCopyUtils(spring 自带的工具类) + HttpServletResponse
@GetMapping("/export2")
public static void exportData2(HttpServletResponse response) {
File file = new File("D:\\Downloads\\Xshell-7.0.0164p.exe");
try (InputStream inputStream = Files.newInputStream(file.toPath())) {
response.setContentType("application/octet-stream");
response.reset();
String filename = URLEncoder.encode(file.getName(), StandardCharsets.UTF_8);
// 处理空格 文件名里的空格会变成+号
filename = filename.replaceAll("\\+", "%20");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
response.addHeader("Content-Length", "" + file.length());
InputStream fis = new BufferedInputStream(inputStream);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
FileCopyUtils.copy(fis, toClient);
} catch (Exception e) {
e.printStackTrace();
}
}
前端就这样,与下载静态资源一样
<a href="/export1">下载</a>
3,如果想用ajax的方式,要自己处理进度条
3.1 jquery 不支持
3.2 原生的xhr 支持
const request = (options = {}) => {
const { url, method, data } = options;
return new Promise((resolve) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === xhr.DONE) {
resolve(xhr.responseText);
}
})
// 提交数据的进度
xhr.upload.addEventListener('progress', (e) => {
// 当前上传的字节长度,总的字节长度
console.log(e.loaded, e.total);
})
// 接受数据的进度
xhr.addEventListener('progress', (e) => {
// 当前接受的字节长度,总的字节长度
console.log(e.loaded, e.total);
})
xhr.open(method, url);
xhr.send(data);
})
}
3.3 fech(只能监听数据的下载进度)
const request = (options = {}) => {
const { url, method, data } = options;
return new Promise(async (resolve) => {
const resp = await fetch(url, {
body: data
})
const total = resp.headers.get('content-length');
const decoder = new TextDecoder();
let body = '';
const reader = resp.body?.getReader();
let loaded = 0;
while (1) {
const { done, value } = await reader?.read();
if (done) {
break;
}
loaded += value.length;
body += decoder.decode(value);
// 数据的总长度,当前接受的长度
console.log(loaded, total)
}
resolve(body)
})
}
3.4 axios
const request = (options = {}) => {
const { url, method, data } = options;
const instance = axios.create({baseURL:'http://127.0.0.1:8887'})
return new Promise(async (resolve) => {
const res = await instance.get('/dubbodemo/tc1/export2', {
responseType: 'blob',
onDownloadProgress: e => {
const total = e.total
const loaded = e.loaded
// 数据的总长度,当前接受的长度
console.log(loaded, total)
},
// `onUploadProgress` 允许为上传处理进度事件
onUploadProgress: function (progressEvent) {
// 处理原生进度事件
},
})
resolve(res.data)
})
}
Disposition 说明:https://blog.csdn.net/m0_46672781/article/details/143159880