Java文件下载controller
时间: 2023-08-15 11:30:34 浏览: 213
在Spring MVC中,可以使用以下的Controller实现文件下载:
```
@Controller
public class FileDownloadController {
private static final int BUFFER_SIZE = 4096;
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取要下载的文件路径
String filePath = "/path/to/file/example.pdf";
File downloadFile = new File(filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// 设置响应头
response.setContentType("application/pdf");
response.setContentLength((int) downloadFile.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFile.getName() + "\"");
// 使用缓冲流读取文件并输出到客户端
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
}
```
这个Controller会接收GET请求,将指定路径下的文件以二进制流形式输出到响应中,使得浏览器会弹出下载文件的对话框。需要注意的是,需要在Spring MVC的配置文件中配置视图解析器和Handler映射。
阅读全文