专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

springmvc文件上传及表单数据封装

补充:

**form表单需要提交时间,**springmvc封装到实体类的Date字段时,丢失时分秒,可以在controller中添加

94_1.png?

1234567891011121314151617 @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } @RequestMapping(value=”/activity”,method = RequestMethod.POST) public String saveActivity(@RequestParam(value = “file”, required = false) MultipartFile file,ImActivityNotifyInfo activityNotifyInfo, HttpServletRequest request, ModelMap model) throws Exception { String fileName = writeFile(file); model.addAttribute(“fileUrl”, request.getContextPath()+”/upload/”+fileName); activityNotifyInfo.setActivityAttach(fileName); activityService.save(activityNotifyInfo); model.addAttribute(“activity”, JsonUtil.toJson(activityNotifyInfo)); return “test”; }

友情链接:个人博客

转载博文:springmvc文件上传

这是用的是SpringMVC-3.1.1、commons-fileupload-1.2.2和io-2.0.1

首先是web.xml

?

123456789101112131415161718192021222324252627282930313233 <web-app version=”2.5″ xmlns=”java.sun.com/xml/ns/java…” xmlns:xsi=”www.w3.org/2001/XMLSch…” xsi:schemaLocation=”java.sun.com/xml/ns/java… java.sun.com/xml/ns/java…“> <servlet> <servlet-name>upload</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>SpringCharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>SpringCharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>/WEB-INF/jsp/user/add.jsp</welcome-file> </welcome-file-list></web-app>

接下来是SpringMVC的配置文件upload-servlet.xml

?

123456789101112131415161718192021222324252627282930313233343536 <beans xmlns=”www.springframework.org/schema/bean…” xmlns:xsi=”www.w3.org/2001/XMLSch…” xmlns:mvc=”www.springframework.org/schema/mvc” xmlns:context=”www.springframework.org/schema/cont…” xsi:schemaLocation=”www.springframework.org/schema/bean… www.springframework.org/schema/bean… www.springframework.org/schema/mvc www.springframework.org/schema/mvc/… www.springframework.org/schema/cont… www.springframework.org/schema/cont…“> <context:component-scan base-package=”com.jadyer”/> <bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name=”prefix” value=”/WEB-INF/jsp/”/> <property name=”suffix” value=”.jsp”/> </bean> <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”> <property name=”defaultEncoding” value=”UTF-8″/> <property name=”maxUploadSize” value=”200000″/> </bean> <bean id=”exceptionResolver” class=”org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”> <property name=”exceptionMappings”> <props> <prop key=”org.springframework.web.multipart.MaxUploadSizeExceededException”>error_fileupload</prop> </props> </property> </bean></beans>

下面是用于上传的表单页面//WEB-INF//jsp//user//add.jsp

?

1234567891011 <%@ page language=”java” pageEncoding=”UTF-8″%><form action=”<%=request.getContextPath()%>/user/add” method=”POST” enctype=”multipart/form-data”> username: <input type=”text” name=”username”/><br/> nickname: <input type=”text” name=”nickname”/><br/> password: <input type=”password” name=”password”/><br/> yourmail: <input type=”text” name=”email”/><br/> yourfile: <input type=”file” name=”myfiles”/><br/> yourfile: <input type=”file” name=”myfiles”/><br/> yourfile: <input type=”file” name=”myfiles”/><br/> <input type=”submit” value=”添加新用户”/></form>

下面是上传成功后打印用户信息的页面//WEB-INF//jsp//user//list.jsp

?

1234567891011 <%@ page language=”java” pageEncoding=”UTF-8″%><%@ taglib prefix=”c” uri=”java.sun.com/jsp/jstl/co…“%><c:forEach items=”94_2.png{user.value.username}—-94_3.png{user.value.password}—-94_4.png{user.value.username}”>查看</a>     <a href=”<%=request.getContextPath()%>/user/94_5.png{user.value.username}/delete”>删除</a> <br/></c:forEach><br/><a href=”<%=request.getContextPath()%>/user/add”>继续添加用户</a>

下面是上传文件内容过大时的提示页面//WEB-INF//jsp//error_fileupload.jsp

?

12 <%@ page language=”java” pageEncoding=”UTF-8″%><h1>文件过大,请重新选择</h1>

接下来是用到的实体类User.java

?

123456789101112131415161718192021 package com.jadyer.model; /** * User * @author 宏宇 * @create May 12, 2012 1:24:43 AM /public class User { private String username; private String nickname; private String password; private String email; /==四个属性的getter()、setter()略==*/ public User() {} public User(String username, String nickname, String password, String email) { this.username = username; this.nickname = nickname; this.password = password; this.email = email; }}

最后是核心的UserController.java

?

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 package com.jadyer.controller; import java.io.File;import java.io.IOException;import java.util.HashMap;import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;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 com.jadyer.model.User; /** * SpringMVC中的文件上传 * @see 第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中 * @see 这里用到的是commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar * @see 第二步:在####-servlet.xml中配置MultipartResolver处理器。可在此加入对上传文件的属性限制 * @see 第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容 * @see 第四步:编写前台表单。注意enctype=”multipart/form-data”以及 * @author 宏宇 * @create May 12, 2012 1:26:21 AM */@Controller@RequestMapping(“/user”)public class UserController { private final static Map<String,User> users = new HashMap<String,User>(); //模拟数据源,构造初始数据 public UserController(){ users.put(“张起灵”, new User(“张起灵”, “闷油瓶”, “02200059”, “menyouping@yeah.net”)); users.put(“李寻欢”, new User(“李寻欢”, “李探花”, “08866659”, “lixunhuan@gulong.cn”)); users.put(“拓拔野”, new User(“拓拔野”, “搜神记”, “05577759”, “tuobaye@manhuang.cc”)); users.put(“孙悟空”, new User(“孙悟空”, “美猴王”, “03311159”, “sunhouzi@xiyouji.zh”)); } @RequestMapping(“/list”) public String list(Model model){ model.addAttribute(“users”, users); return “user/list”; } @RequestMapping(value=”/add”, method=RequestMethod.GET) public String addUser(){ return “user/add”; } @RequestMapping(value=”/add”, method=RequestMethod.POST) public String addUser(User user, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException{ //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解 //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解 //并且上传多个文件时,前台表单中的所有的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件 for(MultipartFile myfile : myfiles){ if(myfile.isEmpty()){ System.out.println(“文件未上传”); }else{ System.out.println(“文件长度: ” + myfile.getSize()); System.out.println(“文件类型: ” + myfile.getContentType()); System.out.println(“文件名称: ” + myfile.getName()); System.out.println(“文件原名: ” + myfile.getOriginalFilename()); System.out.println(“========================================”); //如果用的是Tomcat服务器,则文件会上传到\%TOMCAT_HOME%\webapps\YourWebProject\WEB-INF\upload\文件夹中 String realPath = request.getSession().getServletContext().getRealPath(“/WEB-INF/upload”); //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的 FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename())); } } users.put(user.getUsername(), user); return “redirect:/user/list”; }}

文章永久链接:https://tech.souyunku.com/30028

未经允许不得转载:搜云库技术团队 » springmvc文件上传及表单数据封装

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们