代碼如下:
File file = new File(path);// path是根據(jù)日志路徑和文件名拼接出來(lái)的
String filename = file.getName();// 獲取日志文件名稱(chēng)
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
// 先去掉文件名稱(chēng)中的空格,然后轉(zhuǎn)換編碼格式為utf-8,保證不出現(xiàn)亂碼,這個(gè)文件名稱(chēng)用于瀏覽器的下載框中自動(dòng)顯示的文件名
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(){}這種方法,返回值類(lèi)型為void,調(diào)用時(shí),直接寫(xiě)downloadFile.do就可以出現(xiàn)下載提示框