springMVC文件上传

今天研究了一下springMVC的文件上传,并将步骤和遇到的问题记录下来,大致内容如下:

步骤1.关于jsp编写内容如下:

<form action="upload.do" method="POST" enctype="multipart/form-data">
选择文件:<input type="file" name="file"/>
<input type="submit" value="OK"/>
</form>

这里如果没有enctype="multipart/form-data",程序在运行时会有如下异常:

“ org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.MultipartHttpServletRequest”

在网上查找资料中,出线这个异常的原因都是spring的配置文件编写的不对,但我的程序在spring配置文件正确配置后

还jsp的form中必须需要添加这段文字程序才能正常运行。

步骤2.关于spring配置文件编写内容如下:

<bean id = "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5120000</value>
</property>
<property name="maxInMemorySize">
<value>1024</value>
</property>
</bean>

注意,如果spring配置文件中没有配置或者配置这段代码Bean的id不是multipartResolver,也会在运行时出现步骤1的异常。

3.关于Controller编写内容如下:

@Controller
public class Image {

  @Resource(name = "imageService")
  private ImageService imageService;

  @RequestMapping(value = "JSP/upload", method = RequestMethod.POST)
  public ModelAndView fileUpload(HttpServletRequest request,HttpServletResponse response) throws Exception {
  ModelAndView uploadView = new ModelAndView();
  // 创建文件保存目录
  SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");
  String path = "/shaomch/files/" + dateformat.format(new Date());
  String realPath = request.getSession().getServletContext().getRealPath(path);
  // 根据真实路径创建目录
  File saveFile = new File(realPath);
  if (!saveFile.exists()) {
  saveFile.mkdirs();
  }
  MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
  MultipartFile multipartFile = multipartRequest.getFile("file");
  // 获得文件后缀
  String suffix = multipartFile.getOriginalFilename().substring(
  multipartFile.getOriginalFilename().indexOf("."));
  // 生成文件名
  String fileName = UUID.randomUUID().toString() + suffix;
  String fullFileName = realPath + File.separator + fileName;
  File file = new File (fullFileName);
  try{
    multipartFile.transferTo(file);
  }catch (Exception ex){
    ex.printStackTrace();
  }
  uploadView.addObject("fileMessage", fullFileName);
  uploadView.setViewName("imgload");
  return uploadView;
  }
}

代码很简单,但主要是MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request; 这句话可能在类型转换的时候会出异常。

如果前2步正确配置的话就不会再有问题。

步骤4.commons-fileupload-1.3.1.jar和commons-io-2.4.jar这两个文件需要导入,否则程序也会出现一些其他的错误或者不能执行成功。

以上是springMVC文件上传的4个要点。

原文地址:https://www.cnblogs.com/michaelShao/p/3541502.html