在做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) {}}調用這個程式,當要下載檔案的時候就會彈出一個框框,選擇要下載的路徑就可以儲存檔案到本地了。