java实现下载压缩文件_java实现文件压缩下载----压缩下载zip
文件壓縮下載
Controller層:
/**
*文件壓縮下載
*billname:文件名
*filename:文件存放路徑
*/
public void downloadsource(HttpServletResponse response,String billname,String filename) throws FileNotFoundException, IOException{
//響應(yīng)頭的設(shè)置
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
//設(shè)置壓縮包的名字
//解決不同瀏覽器壓縮包名字含有中文時亂碼的問題
String downloadName = billname+".zip";
//返回客戶端瀏覽器的版本號、類型
String agent = request.getHeader("USER-AGENT");
try {
//針對IE或者以IE為內(nèi)核的瀏覽器:
if (agent.contains("MSIE")||agent.contains("Trident")) {
downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
} else {
//非IE瀏覽器的處理:
downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
}
} catch (Exception e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
//設(shè)置壓縮流:直接寫入response,實現(xiàn)邊壓縮邊下載
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED); //設(shè)置壓縮方法
} catch (Exception e) {
e.printStackTrace();
}
//循環(huán)將文件寫入壓縮流
DataOutputStream os = null;
String modipath = request.getSession().getServletContext().getRealPath("/vod/mp4/"+filename);
File file = new File(modipath);
if(file.exists()){
try {
//添加ZipEntry,并ZipEntry中寫入文件流
//這里,加上i是防止要下載的文件有重名的導(dǎo)致下載失敗
zipos.putNextEntry(new ZipEntry(filename));
os = new DataOutputStream(zipos);
InputStream is = new FileInputStream(file);
byte[] b = new byte[100];
int length = 0;
while((length = is.read(b))!= -1){
os.write(b, 0, length);
}
is.close();
zipos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
//關(guān)閉流
try {
os.flush();
os.close();
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
總結(jié)
以上是生活随笔為你收集整理的java实现下载压缩文件_java实现文件压缩下载----压缩下载zip的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java io nio aio_Java
- 下一篇: java action 上传文件_Jav