使用springmvc中ResponseEntity下载文件

来源:互联网 发布:微信招聘制作软件 编辑:程序博客网 时间:2024/06/05 16:35

今天遇见了一个点击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中文乱码问题,待解决。