業務需求,需要做一個導出使用者單據圖檔的功能,需求為:按單據單号分檔案夾分别存儲單據的圖檔!最終導出zip包給使用者。通過網上各種找代碼,寫出一個小demo,供各位看官學習!
// 假裝是一個單據集合
List<String> imgUrls = new ArrayList<>();
imgUrls.add("http://img1.imgtn.bdimg.com/it/u=2171717409,2602158110&fm=26&gp=0.jpg");
imgUrls.add("http://images.ofweek.com/Upload/News/2016-5/Finn/53/20160503055505730.jpg");
imgUrls.add("http://y1.ifengimg.com/a/2016_04/4855d9fcb2ccade.jpg");
try {
//zip包的名稱
String downloadFilename = "圖檔.zip";
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
// 指明response的傳回對象是檔案流
response.setContentType("application/octet-stream");
// 設定在下載下傳框預設顯示的檔案名
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
@Cleanup ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
imgUrls.forEach(i -> {
InputStream fis = null;
try {
// 跨平台建檔案夾和檔案名字
// File.separator 根據作業系統來判斷用什麼檔案分隔符
// 這裡隻建立了一個檔案夾,如果想分類的話,在後面加上想要的檔案夾名稱即可
ZipEntry zipEntry = new ZipEntry("img_download" + File.separator +imgUrls.indexOf(i)+ ".jpg");
// 放到壓縮包裡
zos.putNextEntry(zipEntry);
// 獲得圖檔流
fis = getInputStreamByGet(i);
if (null != fis) {
byte[] buffer = new byte[1024];
int r = 0;
// 從輸入流讀取一定數量的位元組,存到緩存區中
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
}
} catch (Exception e) {
e.printStackTrace();
}
});
zos.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 通過get請求得到讀取器響應資料的資料流
* @param url
* @return
*/
private static InputStream getInputStreamByGet(String url) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
寫到這裡就聯想到用這個方法可以從網上爬一些照片到本地!