1.导入jar包(m)
<!-- 文件上传组件 不同的版本号--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency>
2.导入包之后,需要配置SpringMVC文件上传解析器,在Springmvc配置文件里配置如下。
<!-- 文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大允许上传文件大小,单位byte --> <property name="maxUploadSize" value="100000000"/> </bean>
3.编写JSP代码如下:
<form action="/springmvc01/upload/image.shtml" method="post" enctype="multipart/form-data"> <input type="file" name="userimage" /> <button>提交</button> </form>
4.编写后台代码:
/*** * 文件上传 * @param session * @param file * @param model * @return * @throws IllegalStateException * @throws IOException */ @RequestMapping(value="/image",method=RequestMethod.POST) public String upload(HttpSession session,@RequestParam(value="userimage")MultipartFile file,Model model) throws IllegalStateException, IOException{ //文件上传路径 String path = session.getServletContext().getRealPath("/upload"); //文件名字 String fname = (int)(Math.random()*10000)+file.getOriginalFilename(); file.transferTo(new File(path+"/"+fname)); //文件访问路径 String fileurl = "/upload/"+fname; model.addAttribute("fileurl", fileurl); return "hello"; }