前言
以前用Asp.net MVC+uploadify上传文件,最近学习SpringMVC,所以就用SpringMVC+uploadify做个上传文件的demo。
刚开始用form表单的方式提交,在Controller Action中用@RequestParam MultipartFile file就能拿到上传文件信息。后我直接使用uploadify的方式上传,接口没有做任何调整,上传的过程中报http400, 客户端的请求不符合接口的要求,表单post提交时报文参数是以Form Data方式,而换成uploadify时参数格式则是request payload的方式,所以把接口改写成MultipartServletRequest的方式
开发环境
SpringMVC4、Uploadify、
上传文件的话还需要下载 commons-fileupload ,同时还会下载common-io、common-logging
项目结构
普通表单上传
@RequestMapping("upload")
public @ResponseBody String upload(@RequestParam MultipartFile file) throws IOException {
String path =request.getSession().getServletContext().getRealPath("upload");
File file=new File(path,file.getOriginalFilename());
file.transferTo(file); //保存文件
return "/success";
}
uploadify上传文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>Index #fileQueue {position: absolute;bottom: 0;right: 0;} spring mvc 上传文件
接口
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response){
String path =request.getSession().getServletContext().getRealPath("upload");
MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest)request;
Map map = multipartHttpServletRequest.getFileMap();
System.out.println("path:"+path);
File file=new File(path);
if(!file.exists()){
file.mkdirs();
}
try{
for(Map.Entry entity:map.entrySet()){
MultipartFile multipartFile=entity.getValue();
File ff = new File(path,multipartFile.getOriginalFilename());
multipartFile.transferTo(ff);
}
return "success";
}catch (Exception e){
e.printStackTrace();
return "error";
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对考高分网的支持。



