首页 > 代码库 > Spring MVC 文件上传
Spring MVC 文件上传
1.form的enctype=”multipart/form-data” 这个是上传文件必须的
2.applicationContext.xml中 <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/> 关于文件上传的配置不能少
3.需要commons.fileupload和commons.io的jar包
Spring的配置文件
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --> <property name="maxUploadSize" value="200000"/> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/ftl/common/error_fileupload.ftl页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/common/error_fileupload</prop> </props> </property> </bean>
Controller
package com.zyz.action;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;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;import javax.servlet.http.HttpServletRequest;import java.io.File;import java.util.Date;/** * Created by zyz on 2016-8-26. */@Controllerpublic class UploadAction { @RequestMapping(value = "/uploadform",method = RequestMethod.GET) public String uploadForm(){ return "uploadForm"; } @RequestMapping(value = "/upload",method = RequestMethod.POST) public String upload(@RequestParam(value = "http://www.mamicode.com/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 "uploadResult"; }}
Spring MVC 文件上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。