Java檔案下載功能實現__Java

來源:互聯網
上載者:User

在做web開發的時候,常常會有這樣的功能,比如說匯出成excel、pdf、txt等,將讀取要匯出的資料,然後產生臨時檔案,然後調用一個下載的子程式。現在我們來說說這個下載子程式怎麼寫吧。

首先產生的臨時檔案肯定是有臨時路徑的tmpFileName,然後我們下載是需要檔案名稱fileName的吧,接下來貼上我寫的這個子程式的原始碼:

public static void downloadFile(String fileName, String tmpFileName, HttpServletRequest request, HttpServletResponse response) throws IOException {if(StringUtils.isEmpty(fileName) && StringUtils.isEmpty(tmpFileName)){return;}File file = new File(tmpFileName);if(!file.exists()) {return;}String postfix = tmpFileName.substring(tmpFileName.lastIndexOf("."));response.reset();String userAgent = request.getHeader("User-Agent");if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "utf-8") + postfix+"\"");} else {fileName = new String(fileName.getBytes("utf-8"),"ISO-8859-1"); // 下載的檔案名稱顯示編碼處理response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + postfix+"\"");}response.setContentType("application/x-msdownload;charset=UTF-8"); FileInputStream fis = new FileInputStream(file);BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());byte[] buffer = new byte[2048];int readlength = 0;while((readlength = fis.read(buffer)) != -1){bos.write(buffer,0,readlength); }try {fis.close();} catch (IOException e) {}try {bos.flush();bos.close();} catch (IOException e) {}}
調用這個程式,當要下載檔案的時候就會彈出一個框框,選擇要下載的路徑就可以儲存檔案到本地了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.