@RequestMapping(value = "/downLoadFile", method = RequestMethod.GET) public void downLoadFile(HttpServletResponse response) throws Exception { // 创建图片URL的地址 List<String> urls = new ArrayList<>(); urls.add("/g1/M00/2B/87/rBBrBlpdfamACuzRAA6DWWpqXtk256.jpg"); ... //创建map用于存放从服务器下载的图片流文件 Map<String, InputStream> isMap = Maps.newHashMap(); urls.forEach(urlStr -> { //分解图片文件名 String[] fileNameParts = urlStr.split("/"); String fileName = fileNameParts[fileNameParts.length - 1]; try { //创建URL对象用于连接存放图片的服务器 URL url = new URL(urlStr); //建立连接 URLConnection con = url.openConnection(); // 设置超时间为3秒 con.setConnectTimeout(3 * 1000); // 防止屏蔽程序抓取而返回403错误 con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //从服务器下载图片流文件 InputStream is = con.getInputStream(); //将图片流文件放入isMap中 isMap.put(fileName, is); } catch (Exception e) { e.printStackTrace(); } }); //设置浏览器返回体的内容以及编码、文件名字 response.setContentType("application/octet-stream"); String filename = URLEncoder.encode("文件名字", "UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".zip"); //创建ZipOutputStream对象,先是获取到response对象的输出流对象,把它转成ZipOutputStream对象,然后给ZipOutputStream流里写入文件的信息,就会同步设置在response的输出流里了 ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream()); isMap.forEach((fileName, is) -> { try { addToZip(is, zipOut, fileName); } catch (Exception e) { e.printStackTrace(); } }); zipOut.flush(); zipOut.close(); } private void addToZip(InputStream is, ZipOutputStream zipOut, String fileName) throws IOException { fileName = URLEncoder.encode(fileName, "UTF-8"); ZipEntry entry = new ZipEntry(fileName); zipOut.putNextEntry(entry); int len; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) > 0) { zipOut.write(buffer, 0, len); } zipOut.closeEntry(); is.close(); }
springMVC实现图片打包下载
最新推荐文章于 2023-12-22 11:21:20 发布
该博客介绍了一个SpringMVC控制器方法,用于处理GET请求并打包多个图片为ZIP文件供用户下载。首先,它创建一个包含图片URL的列表,然后遍历这些URL,从服务器下载图片流并存入Map中。接着,通过设置HTTP响应的Content-Type和Content-Disposition头,使浏览器以附件形式下载ZIP文件,并创建ZipOutputStream以将图片流压缩到ZIP文件中。最后,使用addToZip方法将每个图片流添加到ZIP输出流中,完成打包过程。
4278

被折叠的 条评论
为什么被折叠?



