JavaWeb文件下載功效實例代碼。本站提示廣大學習愛好者:(JavaWeb文件下載功效實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是JavaWeb文件下載功效實例代碼正文
在任務中碰到的一個下載文件的功效,本身將其抽掏出來,代碼簡略,願望能幫到年夜家,好了,話不多說,上代碼!
public void downloadFile(File file, String downName, HttpServletRequest request, HttpServletResponse response) { OutputStream out = null; FileInputStream fin = null; BufferedInputStream bin = null; try { if (file.exists()) { String finalFileName = null; String agent = request.getHeader("User-Agent"); boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1); if (isMSIE) { finalFileName = URLEncoder.encode(downName, "UTF8"); } else { finalFileName = new String(downName.getBytes("UTF-8"), "ISO-8859-1"); } response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=".concat(finalFileName)); out = response.getOutputStream(); fin = new FileInputStream(file); bin = new BufferedInputStream(fin); for (int data = bin.read(); data > -1; data = bin.read()) { out.write(data); } } else { } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bin != null) bin.close(); if (fin != null) fin.close(); if (out != null) out.close(); } catch (Exception e2) { e2.printStackTrace(); } } }
以上就是本文JavaWeb文件下載的代碼,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。