今天在JS中寫了個連接去下載一個TXT,但是發現這種能被瀏覽器解析的文件瀏覽器是不會下載的而是直接打開,這個時候就需要用到下面的方法。(ps需要用到兩個jar包:commons-fileupload.jar和commons-io.jar)
@AutoWrite
ServletContext servletContext;
@RequestMapping("download.do")
public void fileDownload(HttpServletResponse response, String fileName){
//獲得根路徑
String path = servletContext.getRealPath("/");
//自動判斷下載類型
response.setContentType("multipart/form-data");
//設置響應頭,讓瀏覽器下載而不是打開 downloadName是下載下來之後的文件名
response.setHeader("Content-Disposition","attachment;fileName="+downloadName);
File file = new File(path+fileName);
try{
FileInputStream fi = new FileInputStream(file);
ServletOutputStream out = servletContext.getOutputStream();
int b =0;
byte[] byte = new byte[512];
while(b != -1){
b = fi.read(byte);//讀
out.write(byte,0,b);//寫
}
}catch(IOException e){
e.printStackTrace();
}finally{
inputStream.close();
out.close();
out.flush();
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}