java web輸出壓縮檔案到網頁
後臺程式碼:
public void process(HttpServletRequest req, HttpServletResponse res) {
// excel所在目錄
String path = req.getRealPath("") + File.separator + "excel"
+ File.separator + "province";
File[] files = new File(path).listFiles();
String zipFilePath = path+File.separator+"tmp.zip";
ZipFileUtil.compressFiles2Zip(files, zipFilePath);
File zipFile = new File(zipFilePath);
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(zipFile));
byte[] buffer = new byte[2048];
res.setContentType("application/octet-stream");
res.setHeader("Content-Disposition", "attachment; filename=省級大綱表計算.zip");
int len = 0;
ServletOutputStream os = res.getOutputStream();
while((len = in.read(buffer))!=-1){
os.write(buffer,0,len);
}
in.close();
os.flush();
os.close();
zipFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("匯出完成。");
}
前臺程式碼:
$("#download").click(
function(){
var url = "<mellon:root/>/basedata?command=ProvinceFigureDown";
window.location.href = url;
}
);