本来需要实现一个下载压缩文件的功能的,可是下载下来的压缩文件里却没有内容,所以我直接改为绝对路径,并改为其他文件(如图片,txt文本),结果下载下来的内容根本就与源文件内容不同
@RequestMapping("/test")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
File file = new File("E:\\壁纸\\新建文本文档.txt");
byte[] body = null;
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + file.getName());
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
源下载文件
下载之后的文件内容
这是我下载压缩文件的代码,下载其他文件的结果也是跟上面一样
// 节目单保存地址
@Value("${task.savePath}")
private String baseSavePath;
@RequestMapping(value = "/download_task")
public ResponseEntity<byte[]> downloadTask(@RequestParam("taskId")Long taskId, HttpServletRequest request, Model model) throws IOException {
if (taskId == null || !CommonUtils.isIntThanZero(taskId.intValue())) {
return null;
}
// tomcat tmp 文件夹路径
String savePath = System.getProperty("java.io.tmpdir");
// 压缩节目单文件
String fileName = manaProgramTaskService.zipTask(taskId, savePath);
File file = new File(savePath + "/" + fileName);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
可以参考一下:http://www.iteye.com/topic/11...