Spring MVC下载功能
/**
* 导出CSV
*/
@RequestMapping("/exportCSV.do")
public ResponseEntity<byte[]> exportCSV(){
ResponseEntity<byte[]> resEntity = null;
try {
String fileName="lry.csv";
HttpHeaders headers = new HttpHeaders();
//返回下载类型
headers.setContentType(new MediaType("application","csv"));
headers.add("Content-Disposition","attchement;filename=" + fileName);
HttpStatus statusCode = HttpStatus.OK;
resEntity = new ResponseEntity<byte[]>(fileToByteArrChannel("D:/lry.csv"), headers, statusCode);
} catch (Exception e) {
e.printStackTrace();
}
return resEntity;
}
public byte[] fileToByteArrChannel(String path) throws Exception {
FileChannel fc = null;
RandomAccessFile raFile=null;
byte[] result=null;
try {
raFile = new RandomAccessFile(path, "r");
fc =raFile.getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,fc.size()).load();
result= new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
byteBuffer.get(result, 0, byteBuffer.remaining());
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if(fc!=null){
try {
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raFile!=null){
try {
raFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
赞(1)
赏