JAVA 根据Url把多文件打包成ZIP下载实例
程序员文章站
2024-02-15 20:04:34
压缩文件代码工具类:
public class urlfilestozip {
private static final logger logger = lo...
压缩文件代码工具类:
public class urlfilestozip { private static final logger logger = loggerfactory.getlogger(urlfilestozip.class); //根据文件链接把文件下载下来并且转成字节码 public byte[] getimagefromurl(string urlpath) { byte[] data = null; inputstream is = null; httpurlconnection conn = null; try { url url = new url(urlpath); conn = (httpurlconnection) url.openconnection(); conn.setdoinput(true); // conn.setdooutput(true); conn.setrequestmethod("get"); conn.setconnecttimeout(6000); is = conn.getinputstream(); if (conn.getresponsecode() == 200) { data = readinputstream(is); } else { data = null; } } catch (malformedurlexception e) { logger.error("malformedurlexception", e); } catch (ioexception e) { logger.error("ioexception", e); } finally { try { if (is != null) { is.close(); } } catch (ioexception e) { logger.error("ioexception", e); } conn.disconnect(); } return data; } public byte[] readinputstream(inputstream is) { bytearrayoutputstream baos = new bytearrayoutputstream(); byte[] buffer = new byte[1024]; int length = -1; try { while ((length = is.read(buffer)) != -1) { baos.write(buffer, 0, length); } baos.flush(); } catch (ioexception e) { logger.error("ioexception", e); } byte[] data = baos.tobytearray(); try { is.close(); baos.close(); } catch (ioexception e) { logger.error("ioexception", e); } return data; } }
控制层代码:
public void filesdown(httpservletresponse response){ try { string filename = new string("xx.zip".getbytes("utf-8"), "iso8859-1");//控制文件名编码 bytearrayoutputstream bos = new bytearrayoutputstream(); zipoutputstream zos = new zipoutputstream(bos); urlfilestozip s = new urlfilestozip(); int idx = 1; for (string onefile : urls) { zos.putnextentry(new zipentry("profile" + idx); byte[] bytes = s.getimagefromurl(onefile); zos.write(bytes, 0, bytes.length); zos.closeentry(); idx++; } zos.close(); response.setcontenttype("application/force-download");// 设置强制下载不打开 response.addheader("content-disposition", "attachment;filename=" + filename);// 设置文件名 outputstream os = response.getoutputstream(); os.write(bos.tobytearray()); os.close(); } catch (filenotfoundexception ex) { logger.error("filenotfoundexception", ex); } catch (exception ex) { logger.error("exception", ex); } } }
注意:
1. string filename = new string(“xx.zip”.getbytes(“utf-8”), “iso8859-1”);
包装zip文件名不发生乱码。
2.一定要注意,否则会发生下载下来的压缩包无法解压。在给outputstream 传值之前,一定要先把zipoutputstream的流给关闭了!
总结
以上所述是小编给大家介绍的java 根据url把多文件打包成zip下载,希望对大家有所帮助
上一篇: iOS身份证号码识别示例
下一篇: IOS 开发之触摸事件详细介绍