springmvc实现⽂件上传并携带其他参数的⽰例
这是主要使⽤到的jar ⽂件是:spring mvc +apache common-fileuplad
第⼀步:l ⽂件。【重点是spring mvc的和相关】
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="java.sun/xml/ns/javaee"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="java.sun/xml/ns/javaee
java.sun/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- Spring和mybatis的配置⽂件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>l</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring -->
<listener>
<listener-class>org.t.ContextLoaderListener</listener-class>
</listener>
<!-- 防⽌Spring内存溢出 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>l</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
springmvc的注解有哪些</welcome-file-list>
</web-app>
第⼆步:spring-mvc 配置⽂件【重点:spring mvc 视图模式,spring mvc ⽂件上传限定参数,spring mvc 资源拦截管理和其他】
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"
xmlns:context="/schema/context"
xmlns:mvc="/schema/mvc"
xsi:schemaLocation="/schema/beans
/schema/beans/spring-beans-3.1.xsd
/schema/context
/schema/context/spring-context-3.1.xsd
/schema/mvc
/schema/mvc/spring-mvc-4.0.xsd">
<!-- ⾃动扫描该包,使SpringMVC认为包下⽤了@controller注解的类是控制器 -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<context:annotation-config/>
<context:component-scan base-package="com" />
<!--避免IE执⾏AJAX时,返回JSON出现下载⽂件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.verter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的⽂件的前后缀,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这⾥的配置我的理解是⾃动给后⾯action的⽅法return的字符串加上前缀和后缀,变成⼀个可⽤的url地址 -->
<property name="prefix" value="/backstage/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置⽂件上传,如果没有使⽤⽂件上传可以不⽤配置,当然如果不配,那么配置⽂件中也不必引⼊上传组件包 -->  <bean id="multipartResolver"
class="org.springframework.web.multipartmons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- ⽂件⼤⼩最⼤值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最⼤值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
<!-- 声明DispatcherServlet不要拦截下⾯声明的⽬录  -->
<mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/common/" mapping="/common/**"/>
</beans>
第三步:jsp 页⾯
<%@ page language="java" pageEncoding="UTF-8"%>
<form action="<%=ContextPath()%>/users/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/>
<input type="submit" value="添加新⽤户"/>
</form>
第四步:spring mvc 控制器代码
package ller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apachemons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;
import del.News;
import com.wlsq.service.IUserMapperService;
import com.wlsq.util.Pagination;
@Controller
@RequestMapping(value="/users")
public class UserController {
@Autowired
private IUserMapperService userService;
@RequestMapping(value="/userAll")
public ModelAndView searchNews(HttpServletRequest request,HttpServletResponse response){
ModelAndView mv = null;
try{
mv = new ModelAndView();
int pageSize = Integer
.
Parameter("pageSize") == null ? "10"
: Parameter("pageSize"));
int pageNum = Integer
.Parameter("pageNum") == null ? "1"
: Parameter("pageNum"));
Map<String, Object> maps = new HashMap<>();
maps.put("pageSize", pageSize);
maps.put("pageNum", (pageNum-1) * pageSize);
List<News> list =userService.selectAllUsers(maps);
int count = userService.selectCountUsers();
Pagination page = new Pagination(count);
page.setCurrentPage(pageNum);
mv.addObject("pnums", PageNumList());
mv.addObject("currentPage", pageNum);
mv.addObject("pnext_flag", Enable());
mv.addObject("plast_flag", page.lastEnable());
page.lastPage();
mv.addObject("last_page", CurrentPage());
mv.addObject("count", count);
mv.addObject("pageCount", Pages());
if(list !=null && list.size()>0){
//⽤户存在
mv.addObject("partners", list);
//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页⾯
mv.setViewName("/users/users");
}else{
//⽤户存在
mv.addObject("partners", list);
//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页⾯
mv.setViewName("/users/users");
}
}catch(Exception e){
//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页⾯
mv.setViewName("/users/users");
}
return mv;
}
@RequestMapping(value="/add", method=RequestMethod.POST)
public String addUser(@RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException{    String username = Parameter("username");
String nickname = Parameter("nickname");
String password = Parameter("password");
String email = Parameter("email");
System.out.println("name:"+username);
System.out.println("nickname:"+nickname);
System.out.println("password:"+password);
System.out.println("email:"+email);
//如果只是上传⼀个⽂件,则只需要MultipartFile类型接收⽂件即可,⽽且⽆需显式指定@RequestParam注解
//如果想上传多个⽂件,那么这⾥就要⽤MultipartFile[]类型来接收⽂件,并且还要指定@RequestParam注解
//并且上传多个⽂件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数⾥的myfiles⽆法获取到所有上传的⽂件    for(MultipartFile myfile : myfiles){
if(myfile.isEmpty()){
System.out.println("⽂件未上传");
}else{
System.out.println("⽂件长度: " + Size());
System.out.println("⽂件类型: " + ContentType());
System.out.println("⽂件名称: " + Name());
System.out.println("⽂件原名: " + OriginalFilename());
System.out.println("========================================");
//如果⽤的是Tomcat服务器,则⽂件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\⽂件夹中
String realPath = Session().getServletContext().getRealPath("/WEB-INF/upload");
//这⾥不必处理IO流关闭的问题,因为pyInputStreamToFile()⽅法内部会⾃动把⽤到的IO流关掉,我是看它的源码才知道的        InputStream(), new File(realPath, OriginalFilename()));
}
}
return "../../index";
}
}
记得在WEB-INFO建⽴存放上传⽂件⽬录(upload)
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。