Springmvc文件上传


目录
  • Springmvc文件上传
    • 依赖的jar包
    • web.xml相关配置
    • springmvc核心配置文件
    • 单文件上传
      • controller层Java代码
      • 相关jsp代码:upload.jsp
    • 多文件批量上传
      • controller层Java代码
      • 相关jsp代码:batchUpload.jsp
      • index.jsp
    • 项目结构

Springmvc文件上传

依赖的jar包

commons-io
commons-upload

Spring 核心依赖包:bean context aop context core web webmvc expression

web.xml相关配置

<?xml version="1.0" encoding="UTF-8"?>

	springmvc_upload
	
		characterencoding
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	
	
		characterencoding
		*.do
	
	
		upload
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:mvc.xml
		
		1
	
	
		upload
		*.do
	

注意点:

  • springmvc的核心配置文件一定在DispatcherServlet处配置其具体位置,而不是
  • 映射的虚拟路径可以是"/"、"/"、".do"等,但是不要写成"/*.do"

springmvc核心配置文件

<?xml version="1.0" encoding="UTF-8"?>

	
	
	
	
	
	
		
		
	
	
	
		
		
		
	

注意点:

  • 上传的文件大小不得超过文件解析器中maxUploadSize设置的大小,否则会报错
  • 若是在web.xml的url-pattern中设置如/拦截了静态资源,可在此处添加类似这样的设置来放行静态资源,最好把静态资源放置在wencontent下而非WEB-INF(访问权限受限)

单文件上传

controller层Java代码

@Controller
public class UploadCtrl {
	@RequestMapping("/toUpload.do")
	public String toUpload() {
		return "upload";
	}
	@RequestMapping("/upload.do")
	public ModelAndView upload(HttpServletRequest req,@RequestParam("file")CommonsMultipartFile file) {
		String path = req.getServletContext().getRealPath("/upload");
		String name = file.getOriginalFilename();
		System.out.println("文件名:"+name);
		InputStream is = null;
		OutputStream os = null;
		try {
			is = file.getInputStream();
			os = new FileOutputStream(new File(path,name));
			byte[] bytes = new byte[1024];
			int len =0;
			while((len=is.read(bytes))!=-1) {
				os.write(bytes,0,len);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(is!=null)
					is.close();
				if(os!=null)
					os.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		   return new ModelAndView("index");
	}

注意点:

  • CommonsMultipartFile file处必须使用注解@RequestParam("file")为其注入请求中的file属性值,否则CommonsMultipartFile会自己去尝试初始化file,从而报错(找不到CommonsMultipartFile的file值)
  • 通过 "String path = req.getServletContext().getRealPath("/upload");" 将"/upload"这个虚拟路径映射为webcontent下的真实路径。

相关jsp代码:upload.jsp


    
file:

多文件批量上传

controller层Java代码

@RequestMapping("/toBatchUpload.do")
	public String toBatchUpload() {
		return "batchUpload";
	}
	@RequestMapping("/batchUpload.do")
	public ModelAndView batchUpload(HttpServletRequest req,@RequestParam("file")CommonsMultipartFile[] file) {
		String path = req.getServletContext().getRealPath("/upload");
		String name = null;
		InputStream is = null;
		OutputStream os = null;
			byte[] bytes = new byte[1024];
			int len =0;
			for (int i = 0; i < file.length; i++) {
				try {
					name = file[i].getOriginalFilename();
					is = file[i].getInputStream();
					System.out.println("文件名:"+name);
					os = new FileOutputStream(new File(path,name));
					while((len=is.read(bytes))!=-1) {
						os.write(bytes,0,len);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					try {
						if(is!=null)
							is.close();
						if(os!=null)
							os.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return new ModelAndView("index");
	}

通过for循环,重复执行单文件上传代码

相关jsp代码:batchUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Home Page
    <script src="${pageContext.request.contextPath }/js/jquery-2.1.0.min.js" type="text/javascript"></script>


    
file:
<script type="text/javascript"> $("#add").click(function(){ var field = "

选择文件:

"; $("#fileList").append(field); }); function del(obj){ $(obj).parent().remove(); }; </script>

index.jsp


上传成功

注意点:

  • jquery的基本语法就是以function,所以del()函数需要单独定义,而不能将其嵌套在$().ready里面。总结起来就是,使用时可嵌套,但是定义时不可嵌套
  • enctype="multipart/form-data"上传的文件类型不能忘了

项目结构

springmvc_upload

项目源码已上传至 github fileupload