springmvc下载文件
时间: 2023-10-04 08:12:00 浏览: 52
以下是Spring MVC下载文件的示例代码:
@Controller
public class DownloadController {
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletResponse response) throws IOException {
//设置文件名和类型
String fileName = "example.pdf";
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//获取文件流并写入response
InputStream inputStream = this.getClass().getResourceAsStream("/example.pdf");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
}
在这个例子中,我们创建了一个DownloadController类,其中包含一个用于下载文件的方法download。该方法使用HttpServletResponse对象来设置文件名和类型,并获取文件流并写入response。最后,我们调用response的flushBuffer()方法来输出响应并结束请求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)