最近,在項目中遇到了需要將一系列的圖片打包下載的需求,借鑒了網上的一些通用方法,就順便分享出來實現的方法,不太記得借鑒的是哪位兄弟的博客了,總之萬分感謝,進入正題,實現打包下載的基本功能:
1.controller層代碼:
/**
* 圖片壓縮打包
*/
@RequestMapping(value = "/zipFile")
public void compressionFile(HttpServletRequest request, HttpServletResponse response,String busiId) throws Exception{
//業務代碼,根據前台傳來的ID查詢到資源表的圖片list
SubMetaData subMetaData = subMetaDataService.findByBusiId(busiId);
if (subMetaData != null) {
List<SubMetaDataAtt> list = subMetaDataAttService.findByDataId(subMetaData.getDataId());
if (list.size() > 0){
subMetaDataAttService.downloadAllFile(request,response,list);
}
}
}
2.service層通用的文件打包下載
/**
* 將多個文件進行壓縮打包,解決文件名下載后的亂碼問題
*
*/
public void downloadAllFile(HttpServletRequest request, HttpServletResponse response, List<SubMetaDataAtt> list) throws UnsupportedEncodingException{
String downloadName = "附件圖片.zip";
String userAgent = request.getHeader("User-Agent");
// 針對IE或者以IE為內核的瀏覽器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
} else {
// 非IE瀏覽器的處理:
downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
}
//經過上面的名稱處理即可解決文件名下載后亂碼的問題
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", downloadName));
//response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
OutputStream outputStream = null;
ZipOutputStream zos = null;
try {
outputStream = response.getOutputStream();
zos = new ZipOutputStream(outputStream);
// 將文件流寫入zip中,此方法在下面貼出
downloadTolocal(zos,list);
} catch (IOException e) {
logger.error("downloadAllFile-下載全部附件失敗",e);
}finally {
if(zos != null) {
try {
zos.close();
} catch (Exception e2) {
logger.info("關閉輸入流時出現錯誤",e2);
}
}
if(outputStream != null) {
try {
outputStream.close();
} catch (Exception e2) {
logger.info("關閉輸入流時出現錯誤",e2);
}
}
}
}
3.前台js的請求方法:
注:文件的下載不要使用AJAX請求的方法,這樣是無法響應請求的,一般會采用Window.open的方法。
window.open(context+"/sub/submetadataatt/zipFile?busiId="+downloadId);//這里的downloadId是我需要傳到后台的變量。
總結:關於上傳,下載的操作,實際上是要對於java的IO十分熟悉,才可以玩的轉,大家一定要把握好基礎才可以在項目中游刃有余,不像我需要去借鑒他人的東西,大家一起努力,加油!
詳細的配置信息可以參考我寫的這篇文章:http://blog.ncmem.com/wordpress/2019/08/28/java%e6%89%b9%e9%87%8f%e4%b8%8b%e8%bd%bd/