|
現(xiàn)在項目里面有個需求,需要把系統(tǒng)產(chǎn)生的日志文件給下載到本地 先獲取所有的日志文件列表,顯示到界面,選擇一個日志文件,把文件名傳到后臺:
File file = new File(path);// path是根據(jù)日志路徑和文件名拼接出來的
String filename = file.getName();// 獲取日志文件名稱
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset(); // 先去掉文件名稱中的空格,然后轉(zhuǎn)換編碼格式為utf-8,保證不出現(xiàn)亂碼,這個文件名稱用于瀏覽器的下載框中自動顯示的文件名
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();
|