虽然网上代码有很多了,但我还是记录一下。这个程序能够下载任何类型的文件。
*前端代码
<!DOCTYPE html>
<html>
<head>
<title>下载文件示例</title>
<script>
function downloadFile() {
var link = document.createElement('a');
link.href = 'http://localhost:8080/download/{filename}';
link.click(); // 触发点击事件
}
</script>
</head>
<body>
<button onclick="downloadFile()">点击下载文件</button>
</body>
</html>
- Java代码
Java代码用SpringBoot实现的,我下面这个只是单纯的Service的代码。
@Override
public void download(HttpServletResponse resp, String filename) throws IOException {
//打开文件
FIleInputStream in =new FileInputStream("文件路径");
byte[] buffer = new byte[1024];
//设置content-type
resp.setContentType("application/octet-stream");
//设置文件头
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//读数据
int len=0;
ServletOutputStream out = resp.getOutputStream();
//将FileInputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端
while((len=in.read(buffer)) > 0){
out.write(buffer, 0,len);
}
in.close();
out.close();
}