final OutputStream out = new FileOutputStream("D:/EDI/EDi.zip"); //實例文件輸出流
ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
//實例化存檔輸出流,工廠方法創建zip的存檔輸出流
// File f1 = new File(file.getPath());
os.putArchiveEntry(new ZipArchiveEntry(file.getName())); //生成存檔文件名
IOUtils.copy(new FileInputStream(file), os); //添加拷貝存檔文件
os.closeArchiveEntry();
os.close();
//*************************
try {
File input = new File("D:/EDI/EDi.zip");//獲得下載文件路徑
contentType="application/octet-stream";
docStream = new FileInputStream(input);//獲得輸入流名稱
contentDisposition =URLEncoder.encode(input.getName() ,"UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "download";
WEBWORK的文件下載機制。使用起來還是比較簡單的。下面是用法說明:
首先在一個ACTION中,如果判斷有權限進行文件下載。
則:
1、讀出該下載文件,并生成一個流。 文件名應當從請求的request中讀出,或從用戶的表中取出。
public String downLoadFile(String fileName){
try {
File input = new File("e:/engilish literature.doc");
docStream = new FileInputStream(input);
contentDisposition = "test.txt";
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "download";
}
2、將輸出導向到一個特殊的RESULT中去。叫做Steam Result。
<action name="register" class="com.job2easy.web.user.RegisterAction">
<result name="success" type="dispatcher">
<param name="location">/home/register-result.jsp</param>
</result>
<result name="input">
<param name="location">/home/register.jsp</param>
</result>
<result name="download" type="stream">
<param name="contentType">application/x-msdownload</param>
<param name="inputName">docStream</param>
<param name="bufferSize">1024</param>
<param name="contentDisposition">attachment;filename="${contentDisposition}"</param>
</result>
<interceptor-ref name="params"/>
</action>
3、這中間有幾個參數需要配置:
contentType設成 application/x-msdownload 就可以。這樣瀏覽器會保證彈出一個下載文件的對話框。
inputName 這個比較重要,這個名字是輸入流的名稱, 以后要steam result的實現類中為根據OGNL的表達式去查找的。
contentDisposition 這個是下載之后,保存在用戶端的文件名稱。${contentDisposition} 看一下代碼。如果寫成上述的方式,就有機會在ACTION中設置文件名。
4、另外一個參數:contentLength就是下載文件的大小,webwork的stream result似乎實現有問題,不能根據文件的大小動態進行設置,只能寫死。
這個參數的意義是告訴瀏覽下載的文件有多大,以便瀏覽器正確的顯示進度條。如果這個功能很重要的話,可以重新寫一個RESULT來實現。