前后端分别实现
前端代码
const downloadFile = () => {
fetch("/getDocx?fileName=文件名称.docx").then((response) => {
console.log('response :>> ', response);
if (!response.ok) {
throw new Error("本次请求出错!");
}
// 获取文件名
const disposition = response.headers.get("Content-Disposition");
const fileNameMatch = disposition && disposition.match(/filename=(.+)/);
const fileName = fileNameMatch
? fileNameMatch[1]
: "downloaded-file.docx";
const resultFileName = decodeURIComponent(fileName);
// 创建 blob 对象并下载文件
return response.blob().then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = resultFileName; // 设置文件名称
a.click(); // 下载文件
a.remove(); // 移除组件
window.URL.revokeObjectURL(url); // 释放 blob 对象
});
});
};
后端代码
@GetMapping("/getDocx")
public ResponseEntity<byte[]> getDocx(@RequestParam String fileName) {
// 获取模版文件
Resource resource = new ClassPathResource(String.format("/templete/%s",fileName));
try (InputStream inputStream = resource.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 返回的二进制数据
byte[] byteArray = outputStream.toByteArray();
// 设置浏览器识别文件请求头
HttpHeaders headers = new HttpHeaders();
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+encodedFileName);
headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream"); // 适用于所有二进制类型
return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(new byte[0], HttpStatus.NOT_FOUND);
}
}
如果对ResponseEntity不熟悉可以采取HttpServletResponse直接写入到响应体中
@GetMapping("/getDocx")
public void getDocx(@RequestParam String fileName, HttpServletResponse response) {
// 获取模版文件
Resource resource = new ClassPathResource(String.format("/templete/%s", fileName));
try (InputStream inputStream = resource.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ServletOutputStream output = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 返回的二进制数据
byte[] byteArray = outputStream.toByteArray();
// 设置浏览器识别文件请求头
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFileName);
response.setHeader(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
output.write(byteArray);
output.flush();
} catch (IOException e) {
e.printStackTrace();
response.setStatus(HttpStatus.NOT_FOUND.value());
}
}
这两种方式都可以实现对文件的下载,可以随意扩展。
标签:outputStream,const,Spring,Boot,fileName,new,byte,response,下载 From: https://blog.csdn.net/weixin_62759738/article/details/142029723