自定義批量圖片打包下載
請求的方法:
@RequestMapping("/batchDownload")
public void batchCode(HttpServletRequest request, HttpServletResponse response, String tables) throws Exception {
byte [] data = photoImgService.downloadItemImage(tables.split(","));
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"images.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
IOUtils.closeQuietly(response.getOutputStream());
}
/**
*自定義批量下載圖片實現
* @throws Exception
*/
@Override
public byte[] downloadItemImage(String[] tableNames) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
String imagename0 = tableName.substring(tableName.lastIndexOf("/")+1);
String imagename = imagename0.substring(0,imagename0.lastIndexOf("."));
//將當前的圖片放到zip流中傳出去
downLoadImages(tableName,imagename,zip);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 自定義下載圖片方法
* 圖片路徑
* 圖片名稱
* @throws Exception
*
*/
public static void downLoadImages(String imagePath,String imageName,ZipOutputStream zip) throws Exception{
String imgArray[] = {"jpg","png","gif","bmp","jpeg"};
List<String> suffixList = Arrays.asList(imgArray);
String suffix = imagePath.substring(imagePath.lastIndexOf(".") + 1);
if(imagePath!=""&&!imagePath.equals(null)){
BufferedInputStream in = null;
try {
URL url = new URL(imagePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
conn.setRequestProperty(
"Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
+ "application/x-shockwave-flash, application/xaml+xml, "
+ "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
+ "application/x-ms-application, application/vnd.ms-excel, "
+ "application/vnd.ms-powerpoint, application/msword, */*");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setRequestProperty("Charset", "UTF-8");
InputStream inStream = conn.getInputStream();
//校驗讀取到檔案
if (suffixList.contains(suffix)) {// 檔案格式不對
imageName += "."+suffix;
}else {
throw new Exception("不是圖片");
}
if(inStream == null) {
throw new Exception("獲取壓縮的資料項失敗! 資料項名為:" + imageName);
}else {
in = new BufferedInputStream(inStream);
}
//校驗讀取到檔案
// 壓縮條目不是具體獨立的檔案,而是壓縮包檔案列表中的列表項,稱為條目,就像索引一樣
ZipEntry zipEntry = new ZipEntry("圖片/"+imageName);
// 定位到該壓縮條目位置,開始寫入檔案到壓縮包中
zip.putNextEntry(zipEntry);
byte[] bytes = new byte[1024 * 5];// 讀寫緩衝區
int read = 0;
while ((read = in.read(bytes)) != -1) {
zip.write(bytes, 0, read);
}
IOUtils.closeQuietly(inStream);//關掉輸入流
IOUtils.closeQuietly(in);//關掉緩衝輸入流
zip.closeEntry();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
轉載請說明出處:程式設計師花費了很長時間,才搞定的。