这里先说下spring mvc 遇到的坑,就是如果文件上传时,后端这样写public String file1(HttpServletRequest request),根据request拿到的东西是空的。所以要下面这样写。
上传
在任何xml里面(因为都要加载到的,所以可以随便放进去)加上
<bean +f.getAbsoluteFile());
} else {
System.out.println(f.getAbsoluteFile());
}
researchfile(f);
}
}
}
}
下载代码
@RequestMapping("download")
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String filename="报名照片.jpg";
String filePath = "D:/NewFile" ;
File file = new File(filePath + "/" + filename);
if(file.exists()){ //判断文件父目录是否存在
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + new String("报名照片.jpg".getBytes("gb2312"),"ISO_8859_1"));
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
上面红色代码很重要,是让系统返回的不是页面,而是类似文件流的形式输出。其次还
解决Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name) 中文显示乱码
详细的配置信息可以参考这篇文章:http://blog.ncmem.com/wordpress/2019/08/07/java%E8%B6%85%E5%A4%A7%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/