SpringMVC框架
9.2 文件上传示例
- 拷贝jar包
commons-fileupload-1.2.1.jar commons-io-2.0.jar |
严重: Servlet /SpringMVC_06_FileUpload threw load() exception java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory |
- 配置文件上传解析器
<!-- 配置文件上传解析器 id必须是"multipartResolver",否则,会报错误: java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured? --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean> |
- 上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="testUpload" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="file"/><br><br> 描述: <input type="text" name="desc"/><br><br> <input type="submit" value="提交"/> </form> </body> </html> |
- 控制器方法
package com.atguigu.springmvc.crud.handlers; import java.io.IOException; import java.io.InputStream; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadHandler { @RequestMapping(value="/testUpload",method=RequestMethod.POST) public String testUpload(@RequestParam(value="desc",required=false) String desc, @RequestParam("file") MultipartFile multipartFile) throws IOException{ System.out.println("desc : "+desc); System.out.println("OriginalFilename : "+multipartFile.getOriginalFilename()); InputStream inputStream = multipartFile.getInputStream(); System.out.println("inputStream.available() : "+inputStream.available()); System.out.println("inputStream : "+inputStream); return "success"; //增加成功页面: /views/success.jsp } } |