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就可以出現下載提示框