用HttpServletResponse写一个下载文件的代码示例
时间: 2023-09-29 22:10:58 浏览: 86
好的,以下是一个简单的示例代码,可以使用 HttpServletResponse 下载文件:
```java
@RequestMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
// 设置要下载的文件路径和名称
String filePath = "C:/example/file.pdf";
String fileName = "file.pdf";
File file = new File(filePath);
// 设置响应头
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 将文件写入响应输出流
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
```
这个示例代码会将指定路径下的文件以附件形式下载到客户端。
阅读全文