Java 檔案下載原理 + Struts2檔案下載原理 詳解:~~Myself__Java
來源:互聯網
上載者:User
###struts2 完成檔案下載: 1.首先明確基礎知識:InputStream與FileInputStream等都是對記憶體而言, 那麼檔案輸入資料流一定是向記憶體輸入資料流,這對檔案下載是有用的。 本質理解下載檔案過程: 第一步:就是要下載的檔案放到或叫關聯到輸入資料流中: 把檔案幹到記憶體 new FileInputStream("d:\\test.txt") 第二步:把輸入資料流轉換成輸出資料流,即data從記憶體幹到檔案當中去,由此完成了檔案下載功能。 YE的IP抓包下載Excel原理 就是利用這種輸出資料流的方式: InputStream in=new FileInputStream(temp); outStream(in); temp.delete(); 第三步:再配合以下對瀏覽器的控制: getResponse().setContentType("application/vnd.ms-excel; charset=GBK"); String fileName=buildTitle()+".xls"; getResponse().setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes("GB2312"),"ISO-8859-1"));
這就是檔案下載的整個原理。
2.struts2下載檔案的套路: 架構確實簡單-->依然用xml的配置方式,代替了繁瑣的寫入程式碼方式。 第一步:在action當中加一個:
public InputStream getInputStream() throws Exception {
return new FileInputStream("d:\\test.txt");
} 第二步:struts.xml中添加配置: <action name="TopExportTxt" class="cn.cstnet.trafficView.action.flow.CatchIPTopAction" > <result name="success" type="stream"> <param name="contentType">text/plain</param> <param name="inputName">inputStream</param> <param name="contentDisposition">attachment;filename="struts2down.txt"</param> <param name="bufferSize">4096</param> </result> </action>
以上兩步就完全搞定,非常犀利,具體用時再修改下達到業務需求即可。