根据文件的远程路径将多文件合并成zip压缩包,然后下载到客户端,并解决火狐浏览器中文文件名乱码问题,下面是代码
package com.test.util; import java.io.BufferedInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; /** * @ClassName: DownLoadUtil * @Description: 下载文件到客户端工具类 * @author xiaojie * @date 2019年11月6日 下午10:15:45 * */ public class DownLoadUtil { public final static String SUFFIX = ".zip"; public static void downLoad(HttpServletResponse response) { List<String> imageList = new ArrayList<String>(); imageList.add("www.baidu.com/image/123.jpg"); imageList.add("www.baidu.com/image/2343.jpg"); imageList.add("www.baidu.com/image/12345.jpg"); BufferedInputStream is = null; ZipOutputStream zos = null; try { String zipName = "保存文件名" + SUFFIX; zipName = URLEncoder.encode(zipName, "UTF-8"); // 指明response的返回对象是文件流 response.setContentType("application/octet-stream; charset=UTF-8"); // 设置在下载框默认显示的文件名,filename*=utf-8'zh_cn'解决火狐浏览器中文名称乱码问题 response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + zipName); zos = new ZipOutputStream(response.getOutputStream()); for (String image : imageList) { URL url = new URL(image); is = new BufferedInputStream(url.openStream()); zos.putNextEntry(new ZipEntry(image)); byte[] buffer = new byte[1024]; int r = 0; while ((r = is.read(buffer)) != -1) { zos.write(buffer, 0, r); } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { //关闭流 is.close(); zos.flush(); zos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }