Java中Spring Controller如何下载文件呢?
下文笔者Spring Controller下载文件的方法分享
实现思路:
借助向HttpServletResponse对象向客户端发送字节流
即可实现数据下载
例:
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void downloadFile(
@PathVariable("file_name") String fileName,
HttpServletResponse response) {
try {
//获取实际文件流
InputStream is = ...;
//将文件流复制到输出流中
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


