我們在使用java下載時候,通常是通過路徑獲取二進制文件,再通過HttpServletResponse發送到前台,現在將多張圖片打包成zip格式進行下載。代碼如下:
ZipOutputStream zos = null; BufferedInputStream br = null; //下載方法 try { //文件的名稱 String downloadFilename = registrationLoginResultVo.getBusinessName()+".zip"; response.reset(); //設置格式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(downloadFilename, "UTF-8")); //ZipOutputStream來對文件壓縮操作 zos = new ZipOutputStream(response.getOutputStream()); //循環下載文件,並將之放到ZipOutputStream中 for (int i = 0; i < filePath.length; i++) { //filePath是下載路徑集合 //fileName是文件名稱 zos.putNextEntry(new ZipEntry(fileName[i]+".jpg")); br = new BufferedInputStream(new FileInputStream(filePath[i])); byte[] buffer = new byte[1024]; int r = 0; while ((r = br.read(buffer)) != -1) { zos.write(buffer, 0, r); } } zos.flush(); } catch (IOException e) { log.error("導出圖片壓縮包錯誤", e); }finally { try { zos.close(); br.close(); } catch (IOException e) { log.error("導出圖片關閉流異常", e); } }
前端使用xhr進行下載
window.img = function img() { var supplierName = $("#businessName").val(); layer.load(2); //下載圖片格式 var fileName = supplierName+".zip"; var url = config.base_server + "路徑?uuid="+uuid var xhr = new XMLHttpRequest(); xhr.open("get", url, true); xhr.responseType = "blob"; xhr.onload = function () { if (this.status == "200") { var content = this.response; var blob = new Blob([xhr.response]); //for IE if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, fileName); } else { var aElem = document.createElement('a'); aElem.download = fileName; aElem.href = window.URL.createObjectURL(blob); aElem.onload = function (e) { window.URL.revokeObjectURL(aElem.href); }; document.body.appendChild(aElem); aElem.click(); document.body.removeChild(aElem); } layer.closeAll(); } }; xhr.setRequestHeader("Authorization", config.getToken()); xhr.send(); };