本來之前寫一個servlet文件下載的,會出現很多問題,英文下載可以,中文下載就出現了亂碼或者沒顯示的情況;
經過優化,封裝成了一個工具類,如果有更好的,還勞煩賜教。
測試代碼文件結構:
package Tool;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadTool {
/**
* 直接可以利用本工具進行文件下載
*
* @param request 傳入servlet中的
* @param response 傳入servlet中的
* @param dir WebRoot下面的目錄,如果是WebRoot/download只需要寫 download
* @param fileName 文件的名字請包含後綴名
*/
public static void down(HttpServletRequest request,
HttpServletResponse response, String dir, String fileName) {
// 發送頭文件,告訴瀏覽器調用下載功能
try {
response.setHeader("Content-Disposition", "attachment;filename="+
new String(fileName.getBytes("utf-8"),"ISO-8859-1"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 獲取絕對路徑
String path = "/" + dir + "/" + fileName;
String realPath = request.getSession().getServletContext()
.getRealPath(path);
System.out.println("realPath:"+realPath);
File file = new File(realPath);
if (file.exists()) {//文件存在纔開始下載
try {
FileInputStream fis = new FileInputStream(file);
ServletOutputStream sos = response.getOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1) {
sos.write(buff, 0, len);
}
// 關閉io流
sos.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}