应项目要求需要将多个存在某url地址的图片,打包为zip下载下来
public void download(HttpServletRequest request, HttpServletResponse response){ try { String downloadFilename = "中文.zip";//文件的名称 downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码 response.setContentType("application/octet-stream");// 指明response的返回对象是文件流 response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名 ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); String[] files = new String[]{"http://xxxx/xx.jpg","http://xxx/xx.jpg"}; for (int i=0;i<files.length;i++) { URL url = new URL(files[i]); zos.putNextEntry(new ZipEntry(i+".jpg")); //FileInputStream fis = new FileInputStream(new File(files[i])); InputStream fis = url.openConnection().getInputStream(); byte[] buffer = new byte[1024]; int r = 0; while ((r = fis.read(buffer)) != -1) { zos.write(buffer, 0, r); } fis.close(); } zos.flush(); zos.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }