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个要点。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值