springmvc响应下载或者打开

Content-Disposition属性有两种类型:inlineattachment

inline:将文件内容直接显示在页面

attachment:弹出对话框让用户下载具体例子:

在页面内打开代码:

1
2
3
4
5
File file = new File("rfc1806.txt");  
String filename = file.getName();
response.setHeader("Content-Type","text/plain");
response.addHeader("Content-Disposition","inline;filename=" + new String(filename.getBytes(),"utf-8"));
response.addHeader("Content-Length","" + file.length());

弹出保存框代码:

1
2
3
4
File file = new File("rfc1806.txt");  
String filename = file.getName();
response.setHeader("Content-Type","text/plain");
response.addHeader("Content-Disposition","attachment;filename=" + new String(filename.getBytes(),"utf-8"));

SpringMVC下载打开文件

1
2
3
4
5
6
7
8
9
10
@RequestMapping("/openFile")
public ResponseEntity<byte[]> openFile(String data) throws Exception{
byte[] buff= ErecordServiceUtil.getFile(sysUser, data);
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.add("Content-Disposition", "inline;filename="+URLEncoder.encode("文件1","utf-8")+System.currentTimeMillis()+".pdf");
HttpStatus status=HttpStatus.OK;
ResponseEntity<byte[]> entity=new ResponseEntity<byte[]>(buff,headers,status);
return entity;
}