首页 / JAVA / JAVA实现边下载边压缩
JAVA实现边下载边压缩
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JAVA实现边下载边压缩,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2601字,纯文字阅读大概需要4分钟。
内容图文
需求:从服务器下载图片。
因为项目前期设置的问题,导致各个项目的图片是分开存放的。客户要求根据项目下载,实现项目下分地方,然后地方目录下是图片
@ResponseBody public void downloadUrl(HttpServletResponse response, HttpServletRequest request){ String sourceFilePath=properties.getString("sourceFilePath");//要下载的文件路径 eavlProName = xxx;//项目名 String downloadName = "xxx.zip"; //下载文件名 String agent = request.getHeader("USER-AGENT"); //浏览器内核信息try { if (agent.contains("MSIE")||agent.contains("Trident")) {// IE downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8"); } else { downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1"); } } catch (Exception e) { e.printStackTrace(); } zip(sourceFilePath, eavlProName, response, downloadName); response.getOutputStream().close(); //这个应该没什么用} privatevoid zip(String souceFileName, String eavlProName, HttpServletResponse response, String downloadName) { File file = new File(souceFileName); try { zip(file, eavlProName, response, downloadName); } catch (IOException e) { e.printStackTrace(); } } privatevoid zip(File souceFile, String eavlProName, HttpServletResponse response, String downloadName) throws IOException { ZipOutputStream out = null; //设置压缩流。 response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\""); try { out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); out.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法 } catch (Exception e) { e.printStackTrace(); } out.setEncoding("gbk"); zip(souceFile, out, eavlProName, eavlProName,null); out.closeEntry(); out.close(); } privatevoid zip(File souceFile, ZipOutputStream out, String base, String eavlProName, Integer i) throws IOException { if (souceFile.isDirectory()) { File[] files = souceFile.listFiles(); if (files.length != 0) { if (i == null || i != 1) { //对于地方目录先不创建,当地方目录下存在项目的截图时,才创建 out.putNextEntry(new ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; } if (i == null) { i = 0; } i++; for (File file : files) { if (i == null || i != 2) { //2地方下面的项目名.这种不创建目录 zip(file, out, base + file.getName(), eavlProName, i); }else { String picPathname =file.getName(); if (picPathname.equals(eavlProName)) { //取对应项目下的文件 zip(file, out, base, eavlProName, i); } } } } } else { if (base.length() > 0) { out.putNextEntry(new ZipEntry(base)); } else { out.putNextEntry(new ZipEntry(souceFile.getName())); } FileInputStream in = new FileInputStream(souceFile); int b; byte[] by = newbyte[1024]; while ((b = in.read(by)) != -1) { out.write(by, 0, b); } in.close(); } }
参考:http://www.jianshu.com/p/7cabe09ce563
原文:http://www.cnblogs.com/baidualiwangyi/p/8046707.html
内容总结
以上是互联网集市为您收集整理的JAVA实现边下载边压缩全部内容,希望文章能够帮你解决JAVA实现边下载边压缩所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。