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>
以上兩步就完全搞定,非常犀利,具體用時再修改下達到業務需求即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.