final OutputStream out = new FileOutputStream("D:/EDI/EDi.zip"); //實(shí)例文件輸出流
ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
//實(shí)例化存檔輸出流,工廠方法創(chuàng)建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);//獲得輸入流名稱(chēng)
contentDisposition =URLEncoder.encode(input.getName() ,"UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "download";
WEBWORK的文件下載機(jī)制。使用起來(lái)還是比較簡(jiǎn)單的。下面是用法說(shuō)明:
首先在一個(gè)ACTION中,如果判斷有權(quán)限進(jìn)行文件下載。
則:
1、讀出該下載文件,并生成一個(gè)流。 文件名應(yīng)當(dāng)從請(qǐng)求的request中讀出,或從用戶(hù)的表中取出。
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、將輸出導(dǎo)向到一個(gè)特殊的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、這中間有幾個(gè)參數(shù)需要配置:
contentType設(shè)成 application/x-msdownload 就可以。這樣瀏覽器會(huì)保證彈出一個(gè)下載文件的對(duì)話(huà)框。
inputName 這個(gè)比較重要,這個(gè)名字是輸入流的名稱(chēng), 以后要steam result的實(shí)現(xiàn)類(lèi)中為根據(jù)OGNL的表達(dá)式去查找的。
contentDisposition 這個(gè)是下載之后,保存在用戶(hù)端的文件名稱(chēng)。${contentDisposition} 看一下代碼。如果寫(xiě)成上述的方式,就有機(jī)會(huì)在ACTION中設(shè)置文件名。
4、另外一個(gè)參數(shù):contentLength就是下載文件的大小,webwork的stream result似乎實(shí)現(xiàn)有問(wèn)題,不能根據(jù)文件的大小動(dòng)態(tài)進(jìn)行設(shè)置,只能寫(xiě)死。
這個(gè)參數(shù)的意義是告訴瀏覽下載的文件有多大,以便瀏覽器正確的顯示進(jìn)度條。如果這個(gè)功能很重要的話(huà),可以重新寫(xiě)一個(gè)RESULT來(lái)實(shí)現(xiàn)。