SpringMVC文件下载

@Override
public ResponseEntity<byte[]> downLoadFiles(String ids) {
String[] idArray = ids.split(",");
ZipOutputStream zipOutStream = null;
FileInputStream fileInputStream = null;
try {
zipOutStream = new ZipOutputStream(new FileOutputStream("borrowFile.zip"));
for (String idStr : idArray) {
Attachment attachment = attachmentService.findById(Long.parseLong(idStr));
OSSObject ossObject = ossClient.getObject(bucketName,path+attachment.getAttachmentName());
zipOutStream.putNextEntry(new ZipEntry(attachment.getAttachmentOriginalName()));
writeToZip(zipOutStream,ossObject.getObjectContent());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
zipOutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fileInputStream = new FileInputStream("borrowFile.zip");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return buildResponseEntity(fileInputStream,"借阅移交清单.zip");
}


private void writeToZip(ZipOutputStream zipOutputStream,InputStream inputStream) throws IOException {
int temp = 0;
while ((temp = inputStream.read()) != -1){
zipOutputStream.write(temp);
}
inputStream.close();
}

/**
* 构建下载类
* @param inputStream 文件输入流
* @param fileName 文件名
* @return
*/
public static ResponseEntity<byte[]> buildResponseEntity(InputStream inputStream,String fileName) {
byte[] body = null;
//获取文件
ResponseEntity<byte[]> response=null ;
InputStream is = null;
try {
is = inputStream;
body = new byte[is.available()];
is.read(body);
HttpHeaders headers = new HttpHeaders();
fileName = URLEncoder.encode(fileName, "UTF-8");
//设置文件类型
headers.add("Content-Disposition", "attchement;filename=" + fileName);
//设置Http状态码
HttpStatus statusCode = HttpStatus.OK;
//返回数据
response = new ResponseEntity<byte[]>(body, headers, statusCode);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null != is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}

posted @ 2018-08-12 12:01  JAGNG  阅读(210)  评论(0)    收藏  举报