下载文件:
(1)获取要下载的文件名,注意编码;
(2)在HttpHeaders中设置以下载方式打开,设置MIME类型;
(3)用FileUtils.readFileToByteArray()读取文件数据;用ResponseEntity构建返回对象
/**
* Create a new {@code HttpEntity} with the given body, headers, and status code.
* @param body the entity body
* @param headers the entity headers
* @param status the status code
*/
public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
super(body, headers);
Assert.notNull(status, "HttpStatus must not be null");
this.status = status;
}
在HttpEntity
类的源码中可以看到: 将header头转变成只能读取的对象,而不是写入的对象
/**
* Create a new {@code HttpEntity} with the given body and headers.
* @param body the entity body
* @param headers the entity headers
*/
public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) {
this.body = body;
HttpHeaders tempHeaders = new HttpHeaders();
if (headers != null) {
tempHeaders.putAll(headers);
}
this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders);
}
JSP页面:
<body>
<c:forEach items="${list}" var="pic">
<img src="${pic }" />
<a href="down.action?fileName=${pic }">下载${fn:substringAfter(pic,'/') }</a><p/>
</c:forEach>
</body>
Controller代码:
@RequestMapping("/down")
public ResponseEntity<byte[]> down( HttpServletRequest request,String fileName) throws Exception {
// D:\apache-tomcat-7.0.82\webapps\springmvc3_20180301_am
//处理中文编码
String myFileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
// 获得服务器路径
String path=request.getSession().getServletContext().getRealPath("");
//获得完整的路径
String string=path+File.separator+fileName;
//输出路径
System.out.println(string);
//设置头信息
HttpHeaders headers=new HttpHeaders();
//设置下载的附件 (myFileName必须处理中文名称哦!)
headers.setContentDispositionFormData("attachment", myFileName);
//设置MIME类型
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//用FileUpload组件的FileUtils读取文件,并构建成ResponseEntity<byte[]>返回给浏览器
//HttpStatus.CREATED是HTTP的状态码201
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(string)),headers,HttpStatus.CREATED);
}
显示:
单击下载: