Spring MVC中的文件下载
1.利用HttpServlet进行文件下载
@RequestMapping("/rc")
@Controller
public class DemoController {
@RequestMapping("/d1")
public void m1(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 获取文件流
ServletContext context = request.getServletContext();
InputStream inputStream = context.getResourceAsStream("/file/blog.png");
// 设置头部响应
// 防止浏览器直接打开
response.setContentType("application/octet-stream");
// 保证保存文件名默认为blog.png
response.setHeader("Content-Disposition","attachment;filename=blog.png");
// 获取输出流
ServletOutputStream outputStream = response.getOutputStream();
// 利用commons的文件流jar
IOUtils.copy(inputStream,outputStream);
}
}
2. 使用MVC风格进行文件下载
@RequestMapping("/rc")
@Controller
public class DemoController {
@Autowired
private WebApplicationContext context;
@RequestMapping("/d2")
public ResponseEntity<Byte[]> m2() throws IOException {
// 拿到ServletContext对象
ServletContext servletContext = context.getServletContext();
// 获取文件全路径
String realPath = servletContext.getRealPath("/file/blog.png");
File file = new File(realPath);
// 利用FileUtils将文件转换成byte数组
byte[] input=FileUtils.readFileToByteArray(file);
// 设置响应头和响应参数
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition","attachment;filename=blog.png");
// 直接将数据返回浏览器ResponseEntity进行解析,状态码设置为ok
return new ResponseEntity(input,headers,HttpStatus.OK);
}
}
文件下载时还涉及默认显示文件名中文乱码的问题,具体设置:
文件下载案例实现