spring-上传功能

来源:互联网 发布:最好的seo 编辑:程序博客网 时间:2024/06/08 12:05
package controller;import java.io.File;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MaxUploadSizeExceededException;import org.springframework.web.multipart.MultipartFile;@Controllerpublic class UploadController {@RequestMapping("/toUpload.do")public String toUpload(){return "upload";}@RequestMapping("/upload.do")public String upload(@RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request,ModelMap model){//request.getRealPath("")   就是取得你当前运行文件在服务器上的绝对路径String path = request.getServletContext().getRealPath("wq");System.out.println(path);//将文件保存的位置String fileName = file.getOriginalFilename();System.out.println(fileName);//文件名字File targetFile = new File(path,fileName);if(!targetFile.exists()){targetFile.mkdirs();}//保存try{file.transferTo(targetFile);//上传文件//将文件的绝对路径保存到ModelMap传给result.jsp页面model.addAttribute("fileUrl",request.getContextPath()+"/wq/"+fileName);}catch(Exception e){e.printStackTrace();}return "result";}/** * 要求:se2.png为文件名,该文件放在wq目录下 * 输出结果如下: * D:\eclipse\apache-tomcat-7.0.67\wtpwebapps\springmvc03\再加上wq * se2.png   * 注意:当点击查看时,可以看见该文件(静态资源) *///处理上传多个文件的请求@RequestMapping("/uploads.do")public String uploads(/** * @RequestParam(value = "file1", required = false): * 将参数中的file1绑定到MultipartFile file1,此时CommonsMultipartResolver * 已经帮我们把附件内容填充到MultipartFile 中了,这里required = false最好设置为false, * 除非你确定这个参数一定会传递给controller,否则会抛出参数绑定异常 */@RequestParam(value="file",required=false) MultipartFile[] files,HttpServletRequest request,ModelMap model){//将文件上传到的位置String path = request.getSession().getServletContext().getRealPath("uploads");List<String> urls = new ArrayList<String>();//文件名的集合for(MultipartFile file : files){String fileName = file.getOriginalFilename();//有可能只上传了部分文件,其余文件名为""if(fileName == null || "".equals(fileName)){continue;}File targetFile = new File(path,fileName);if(!targetFile.exists()){targetFile.mkdirs();}//保存try {file.transferTo(targetFile);urls.add(request.getContextPath()+"/uploads/"+fileName);} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}model.addAttribute("fileUrls",urls);return "result";}@ExceptionHandler//处理总上传文件过大的异常public String exHandle(Exception ex,HttpServletRequest request){//根据异常的不同来处理if(ex instanceof MaxUploadSizeExceededException){request.setAttribute("errorMsg", "文件总内容超过了51200B");return "error";}else{return "system_error";}}}

web.xml文件:

<!-- 配置前端控制器 -->  <servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:springmvc.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>springmvc</servlet-name>    <url-pattern>*.do</url-pattern>  </servlet-mapping>

spring配置文件:

<?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:jdbc="http://www.springframework.org/schema/jdbc"  xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:util="http://www.springframework.org/schema/util"xmlns:jpa="http://www.springframework.org/schema/data/jpa"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsdhttp://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"><!-- 组件扫描对@Component @Service @Repository @Controller这四个有效  --><context:component-scan base-package="controller"></context:component-scan><!-- 配置springmvc注解扫描(spring3.2版本以后使用此配置,之前版本配置有所不同)对@RequestMapping有效 --><mvc:annotation-driven></mvc:annotation-driven><!-- 配置视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  <property name="prefix" value="/WEB-INF/"></property>  <property name="suffix" value=".jsp"></property></bean><!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   <!--    指定所上传文件的总大小不能超过51200B注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和    -->        <property name="maxUploadSize" value="51200"></property>   <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadController 中捕获文件大小异常-->      <property name="resolveLazily" value="true"></property></bean></beans>






原创粉丝点击