SpringMVC 中的上传下载
在使用SpringMVC 做上传时需要做的时在配置文件中配置
<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
</bean>
- bean 中 name 只能是 multipartResolver,在需要使用处理文件上传的方法添加 MultipartFile 参数
@RequestMapping(value="/user/file/upload")
public String upload(HttpSession session,Model model,MultipartFile file,String dir){
//String root=((User)session.getAttribute("user")).getVhost().getDoc_root()+"/"+ParseTools.paramToString(dir)+"/"+file.getOriginalFilename();
//服务器端文件存放的路径
String root="e:/1.txt";
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(root));
model.addAttribute("msg", "上传完成了");
} catch (IOException e) {
e.printStackTrace();
}
return "user/message";
}
下载: 与普通Servlet 下载类似
@RequestMapping(value="/user/file/down")
public ModelAndView down(HttpSession session,HttpServletRequest request,HttpServletResponse response,String f){
String root=((User)session.getAttribute("user")).getVhost().getDoc_root()+"/"+f;
BufferedInputStream bis =null;
BufferedOutputStream bos=null;
try {
response.setHeader("Content-type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename="+new String(f.substring(f.lastIndexOf("/")+1).getBytes("utf-8"), "ISO8859-1"));
bis = new BufferedInputStream(new FileInputStream(root));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
while(bis.read(buff)!=-1){
bos.write(buff);
buff=new byte[2048];
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
System.out.println("down 没有正常关闭");
}
finally{
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
//return "user/file/redownload";
}
不过这里的异常好像拦截不住。 应该tomcat导致的(很多原因说是浏览器没有正常关闭导致的)。直接在控制台拦截不到, 感觉挺奇葩的
Reproduced please indicate the author and the source, and error a link to this page.
text link:
//xiaochun.zrlog.com/62.html