spring-上传功能

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;


@Controller
public 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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://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>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值