您的位置:首页技术文章
文章详情页

前端ajax请求+后端java实现的下载zip压缩包功能示例

【字号: 日期:2022-06-14 13:43:26浏览:7作者:猪猪
ajax请求 下载zip压缩包

后台最主要是 response.setContentType(“application/octet-stream”);以及 response.addHeader(“Content-Disposition”, “attachment;fileName=” + URLEncoder.encode(“图片.zip”, “UTF-8”));

一、后台代码@PostMapping('/downloadZip') public void downloadCerts(HttpServletRequest request, HttpServletResponse response, @RequestBody List<String> ids) throws UnsupportedEncodingException { //文件流octet-streamresponse.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.length ; i++) { if (b[i] <0) {b[i]+=256; }}out.write(b);out.flush();out.close();//到这里 base64 转换成了图片//往zip里面压入第一个文件 本地文件resultStream.putNextEntry(new ZipEntry('本地图片.png' ));InputStream stream = new FileInputStream(new File('temp.png'));int len;// 读入需要下载的文件的内容,打包到zip文件while ((len = stream.read(buffer)) > 0) { resultStream.write(buffer, 0, len);}resultStream.closeEntry();stream.close();resultStream.flush();//第一个文件压入完成 关闭流 刷新一下缓冲区// 往zip里面压入第二个文件 网络文件 例:https://profile.csdnimg.cn/8/C/E/3_blogdevteamresultStream.putNextEntry(new ZipEntry('网络图片.png'));URL url = new URL('https://profile.csdnimg.cn/8/C/E/3_blogdevteam';);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();} }二、前端代码

前端代码比较简单 直接贴出 我使用的是vue的 axios

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里的代码

问题

如果你发现下载的文件比源文件大,很可能是前端请求需要加入以下代码

responseType:'blob',

注意:笔者在测试过程中发现一些网站带有防盗链功能,需要referer验证。另外还可能会出现前端blob格式转换、跨域等诸多问题 ,需要读者酌情处理。

标签: Ajax
相关文章: