SpringMvc下的文件上传
首先是springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 配置自动扫描的包 --> <context:component-scan base-package="springmvc"></context:component-scan> <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value="/WEB-INF/"></property> <property name = "suffix" value = ".jsp"></property> </bean> <!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> </beans>
重点是最后的配置multipartResolver;其次有一个坑就是网上部分教程没告诉我们要引入两个必须的jar包common-fileupload和common-io。
还有一点是form表单中的enctype="multipart/form-data"属性记得配置。
下面是创建目录和文件以及展示上传页面的代码:
package springmvc.action; /** * Created by alden on 2017/1/3. */ import java.io.File; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/Upload") public class UploadController {
//上传界面 @RequestMapping("/UploadPage") public String UploadPage() { return "Upload/UploadFile"; } @RequestMapping(value = "/UploadFile") public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) { System.out.println("开始"); String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); // String fileName = new Date().getTime()+".jpg"; System.out.println(path); File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName); return "Upload/Result"; } }