JavaWeb項目實現文件下載


File file = new File(path);// path是根據日志路徑和文件名拼接出來的
String filename = file.getName();// 獲取日志文件名稱
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名稱中的空格,然后轉換編碼格式為utf-8,保證不出現亂碼,這個文件名稱用於瀏覽器的下載框中自動顯示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);// 輸出文件
os.flush();
os.close();

struts2.0中,可以使用public void downloadFile(){}這種方法,返回值類型為void,調用時,直接寫downloadFile.do就可以出現下載提示框


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM