实现方法如下:
@RequestMapping(value = "/download/file/{method}",method = GET)
public ResponseEntity<byte[]> download(HttpServletRequest request,@PathVariable("method") String method) throws IOException {
HttpHeaders headers = new HttpHeaders();
String fileName=request.getParameter("fileName");
System.out.println(fileName);
List<Charset> list=new ArrayList<Charset>();
list.add(Charset.forName("UTF-8"));
headers.setAcceptCharset(list);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "iso8859-1"));
File file=commandManager.getFile(folderStr+fileName);
if(file!=null){
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}else{
downloadFileMessageWebSocketHandler.sendMessage("文件不存在,请刷新文件列表");
return null;
}
}
downloadFileMessageWebSocketHandler
是我自己写的消息推送类。
实现方法就这么简单,但是有两点需要注意。
- 下载下来的文件显示乱码问题
对于这个问题,需要加上如下配置:
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
需要将这行配置加在json配置前面,如下:
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="com.datatrees.loan.collection.converter.MappingJackson2JsonpHttpMessageConverter" p:supportedMediaTypes="*/*" >
<property name="objectMapper">
<!--convert null to ""-->
<bean class="com.datatrees.loan.collection.global.ObjectMapping"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
- 下载下来的文件名无法显示中文的问题
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "iso8859-1"));
转码就可以了