我们在使用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(); };