使用springmvc中ResponseEntity下载文件
今天遇见了一个点击table列表中文件名,实现下载文件的功能。 因为这边的项目用的springmvc做的容器,以下是通过ajax访问该url通过输入流将数据(该数据通过url携带)中携带的文件内容(content)转换成字节存入缓存中。 通过springmvc封装的下载实现ResponseEntity将字符串输出成.docx文件下载。
第一种方法:
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
通过设置请求体(body),请求头(headers),请求状态(statusCode)传回前端页面。
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@RequestMapping("/download/{content}/{title}")
public ResponseEntity<byte[]> download(HttpServletRequest request,@PathVariable String content ,@PathVariable String title ) throws IOException {
//设置缓存
byte[] body = null;
//字节流读取String数据
ByteArrayInputStream is = new ByteArrayInputStream("content".getBytes());
body = new byte[is.available()];
is.read(body);
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + title+".docx");
//设置请求状态
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
页面不能通过ajax访问url。 必须通过页面window.location.href = resqURL;属性来访问。
设置文件名时,有url中文乱码问题,解决方法。
//设定URLEncoder编码集为utf-8。具体原理可以百度。
String fileName =URLEncoder.encode(title+".doc", "utf-8");
//或者使用ResponseEntity中HttpHeaders headers对象的.add()方法设定报文头
//headers.add("Content-Disposition", "attchement;filename=" + fileName);
上面一种方法因为使用了return,可以会出现在特定的浏览器中自行打开文件,而不是下载,如ie浏览器对word、excel等文件的处理。
第二种方法:
使用servlet的输出流 ServletOutputStream
具体实现和上面相似:
@RequestMapping("/download/{infoId}/{fundCode}")
//这里创建了HttpServletResponse的实例对象。
public void download(@PathVariable String infoId,@PathVariable String fundCode,HttpServletResponse response) throws IOException {
//和上面一样,将content数据使用流放入缓存body中
byte[] body = null;
ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes());
body = new byte[is.available()];
is.read(body);
//将ContentType、Header等需要的设置放进 HttpServletResponse传回前端
String fileName =URLEncoder.encode(title+".doc", "utf-8");
response.setContentType("application/msword");
response.addHeader("Content-Disposition", "attachment;filename=" +fileName);
response.setContentLength(body.length);
//获取Servlet的输出流ServletOutputStream
ServletOutputStream sos = response.getOutputStream();
sos.write(body);
if (sos != null) {
sos.close();
}
}
