通過瀏覽器批量下載檔案到zip壓縮包
阿新 • • 發佈:2020-11-14
/** * 批量下載證件照、檔案 * * @return */ @GetMapping("/downLoadImgs") @Transactional public void downLoadImgs(HttpServletRequest request,@RequestParam(name = "ids", required = true) String ids, HttpServletResponse response) { //1.拿到對應圖片地址的url陣列 String[] array = ids.split(","); ArrayList<String> idList = new ArrayList<>(Arrays.asList(array)); //根據ids查詢出所有的檔案 List<XzFile> xzFiles = xzFileService.selectBatchIds(idList); ArrayList<String> urls = new ArrayList<>(); for (XzFile xzFile : xzFiles) { //todo 在圖片路徑加上字首urls.add("http:*****"+xzFile.getIdPhoto()); } String[] files = new String[urls.size()]; urls.toArray(files); //2.開始批量下載功能 try { // String nowTimeString = TimeUtils.getNowTimeString(); String downloadFilename = "證件照" + ".zip";//檔案的名稱 downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//轉換中文否則可能會產生亂碼 response.setContentType("application/octet-stream");// 指明response的返回物件是檔案流 response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 設定在下載框預設顯示的檔名 ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); for (int i = 0; i < files.length; i++) { URL url = new URL(files[i]); //拿到檔名 String spath=xzFiles.get(i).getIdPhoto(); int pos = spath.lastIndexOf('\\'); String sfilename = spath.substring(pos + 1);//帶副檔名 pos = sfilename.lastIndexOf('.'); String sfilenameEx = sfilename.substring(0,pos);//不帶副檔名 //設定檔名 zos.putNextEntry(new ZipEntry(sfilenameEx + ".jpg")); InputStream fis = url.openConnection().getInputStream(); byte[] buffer = new byte[1024]; int r = 0; while ((r = fis.read(buffer)) != -1) { zos.write(buffer, 0, r); } fis.close(); } zos.flush(); zos.close(); } catch (Exception e) { return ; } }