//controller
@RequestMapping(value = "/downLoadFile")
@ResponseBody
public ResponseEntity<byte[]> downLoadFile() {
return service.downLoadFile();
}
//service
public ResponseEntity<byte[]> downLoadFile(int type) {
HttpHeaders headers = new HttpHeaders();
byte[] bt = null;
try {
String fileName = "测试文档";
String filePath = "/home/doc";
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String path = filePath + File.separator + fileName;
logger.debug("下载路径:" + path);
bt = readFileToByteArray(path);
} catch (Exception e) {
e.printStackTrace();
}
//使用HttpStatus.CREATED IE不支持201,所以需要使用HttpStatus.OK
//return new ResponseEntity<byte[]>(bt, headers, HttpStatus.CREATED);
return new ResponseEntity<byte[]>(bt, headers, HttpStatus.OK);
}
private byte[] readFileToByteArray(String filePath) {
byte[] bt = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
bt = bos.toByteArray();
} else {
logger.error("没有找到文件!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (bos != null)
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bt;
}
转载于:https://my.oschina.net/gmd/blog/598166