- restController的工作
- 首先读取文件
File file = new File(filePath, fileName) InputStream inputStream = new FileInputStream(file);
- 设置response
response.setContentType("application/msword;charset=utf-8"); response.setHeader("Content-Disposition", "attachment");
- 写到输出流
@GetMapping(value = "/download/userguide") public StreamingResponseBody getDocument(HttpServletResponse response) { //read file ... //set response ... //write to outputStream return outputStream -> { int nRead; byte[] data = new byte[1024]; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { outputStream.write(data, 0, nRead); } };
-
response.setContentType()的作用及参数
response.setContentType(MIME)的作用是使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
具体文件类型对应的参数,可以参考下面链接
https://blog.csdn.net/luman1991/article/details/53423305 -
前端下载文件
将button的click响应汉书
<button type="button" (click)="downloadUserguide()" label="下载模板"></button>
downloadUserguide(){
console.log("download user guide");
const link: HTMLElement = document.createElement('a');
link.setAttribute('href', SERVER_API_URL + 'uaa/api/download/userguide');
link.setAttribute('download', 'CPE-UserGuide.docx');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
网友评论