ajax请求 下载zip压缩包
后台最主要是 response.setContentType(“application/octet-stream”);
以及 response.addHeader(“Content-Disposition”, “attachment;fileName=” + URLEncoder.encode(“图片.zip”, “UTF-8”));
一、后台代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | @PostMapping ( "/downloadZip" ) public void downloadCerts(HttpServletRequest request, HttpServletResponse response, @RequestBody List ids) throws UnsupportedEncodingException { //文件流octet-stream response.setContentType( "application/octet-stream" ); response.setCharacterEncoding( "utf-8" ); response.addHeader( "Content-Disposition" , "attachment;fileName=" + URLEncoder.encode( "图片.zip" , "UTF-8" )); try { ZipOutputStream resultStream = new ZipOutputStream(response.getOutputStream()); // 这里是查询数据库 List<map> result = service.downloadCerts(ids); byte [] buffer = new byte [ 10240 ]; for (Map map :result) { //因为数据库保存的是图片的base64 所以需要转换 BASE64Decoder decoder = new BASE64Decoder(); File certFace = new File( "temp.png" ); OutputStream out = new FileOutputStream(certFace); byte [] b = decoder.decodeBuffer(((String) map.get( "certB64" )).split( "," )[ 1 ]); for ( int i = 0 ; i <b> 0 ) { resultStream.write(buffer, 0 , len); } resultStream.closeEntry(); stream.close(); resultStream.flush(); //第一个文件压入完成 关闭流 刷新一下缓冲区 // 往zip里面压入第二个文件 网络文件 例:https://profile.csdnimg.cn/8/C/E/3_blogdevteam resultStream.putNextEntry( new ZipEntry( "网络图片.png" )); String str = url.toString(); URLConnection connection = url.openConnection(); InputStream backStream = connection.getInputStream(); // 读入需要下载的文件的内容,打包到zip文件 while ((len = backStream.read(buffer)) > 0 ) { resultStream.write(buffer, 0 , len); } resultStream.closeEntry(); backStream.close(); resultStream.flush(); //第二个文件压入完成 关闭流 刷新一下缓冲区 } resultStream.close(); //关闭流 } catch (IOException e) { e.printStackTrace(); } }</b></map> |
二、前端代码
前端代码比较简单 直接贴出 我使用的是vue的 axios
1 2 3 4 5 6 7 8 9 10 11 12 13 | download( this .ids).then((response) =>{ if (response.status == 200) { let url = window.URL.createObjectURL( new Blob([response.data])) let link= document.createElement( 'a' ) link.style.display= 'none' link.href=url link.setAttribute( 'download' , "图片.zip" ) // 自定义下载文件名(如exemple.txt) document.body.appendChild(link) link.click() } else { this .$message.error( "下载出错了" ); } }); |
这里的 download(this.ids) 是封装过的axios 重点是 then里的代码
问题
如果你发现下载的文件比源文件大,很可能是前端请求需要加入以下代码
1 | responseType: 'blob' , |
注意:笔者在测试过程中发现一些网站带有防盗链功能,需要referer验证。另外还可能会出现前端blob格式转换、跨域等诸多问题 ,需要读者酌情处理。