SpringMVC上传文件
效果如下
需要新加入的jar包:commons-fileupload-1.3.3.jar,commons-io-2.5.jar
<form action="upload" enctype="multipart/form-data" method="post"> <table> <tr> <td>文件描述</td> <td><input type="text" name="description"></td> </tr> <tr> <td>请选择文件</td> <td><input type="file" name="file"></td> </tr> <tr> <td><input type="submit" value="上传"></td> </tr> </table> </form>
package com.game.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; 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 UpLoadController { @RequestMapping("/{formName}") public String login(@PathVariable String formName) { return formName; } @RequestMapping(value="/upload",method=RequestMethod.POST) public String upload(HttpServletRequest request,@RequestParam("description") String desc,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException { if(!file.isEmpty()) { String path = request.getServletContext().getRealPath("/images/"); String filename = file.getOriginalFilename(); File filepath = new File(path,filename); if(!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } file.transferTo(new File(path + File.separator + filename)); } return "success"; } }
<!-- spring可以自动去扫描base-pack下边的包或者子包下的java类,如果有扫描到spring相关的注解类,则把这些类注册为spring的bean --> <context:component-scan base-package="com.game.controller"></context:component-scan> <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/content/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"></property> <property name="defaultEncoding" value="UTF-8"></property> </bean>