//下载模板
@RequestMapping(value = "/downLoad",method = RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response,String strFileName) throws IOException{
String userAgent = request.getHeader("User-Agent");
//路径为Linux盘符路径
String url = nowUrl+"/"+strFileName;
//C:\Users\Administrator\Desktop\test
//String url="C:/Users/Administrator/Desktop/test/1.xlsx";
File file = new File(url);
String name = file.getName();
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
name = java.net.URLEncoder.encode(name, "UTF-8");
} else {
// 非IE浏览器的处理:
name = new String(name.getBytes("UTF-8"), "ISO-8859-1");
}
//当文件存在
if(file.exists()){
response.setContentType("application/force-download");
response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", name));
byte[]buffer=new byte[1024];
FileInputStream fis=null;
BufferedInputStream bis=null;
try{
fis=new FileInputStream(file);
bis=new BufferedInputStream(fis);
OutputStream os=response.getOutputStream();
//从源文件中读
int i=bis.read(buffer);
while(i!=-1){
//写到response的输出流中
os.write(buffer,0,i);
i=bis.read(buffer);
}
}catch (IOException e){
e.printStackTrace();
}finally {
//善后工作,关闭各种流
try {
if(bis!=null){
bis.close();
}
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
下载模板
最新推荐文章于 2022-06-01 14:25:25 发布