今天在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;
}