SpringMVC file upload: MultipartResolver interface

SpringMVC implements file upload:

Single file upload:

SpringMVC provides direct support for file upload, namely MultipartResolver接口
MultipartResolver interface

Used to process upload requests, package the upload request into data that can directly obtain files, and facilitate the operation of
two implementation classes
StandardServletMultipartResolver: Uses the Servlet3.0 standard upload method
CommonsMultipartResolver: Uses Apache's commons-fileupload to complete the specific upload operation (This article is based on)


The configuration of SpringMvc is omitted:

  1. Import Jar file
    We need Apache component, we need to import two Jar components
    commons-io-2.4.jar
    commons-fileupload-1.2.2.jar

  2. Configure MultipartResolver (in the core configuration file of SpringMVC;)
    Use CommonsMultipartResolver to configure a MultipartResolver resolver

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<property name="maxUploadSize"   value="500000" ></property>
    	<property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- 
    	defaultEncoding	: 请求的编码格式,默认为 ISO-8859-1; 一般设为UTF-8 (defaultEncoding必须和JSP的pageEncoding 设置一致,以便正确读取表单内容)
    	maxUploadSize	: 设置文件上传的大小限制,单位为字节;
     -->
    
  3. Write file upload form page (JSP HTML...)


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>	<!-- pageEncoding="UTF-8" 与MultipartResolver文件上传解析编码设置一致 -->
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
  
	<!-- 
		action="myupload" 				: Springmvc控制器接收的名
		method="post" 					: 提交方式,文件上传必须是 post; get存储太小了且不安全;
		enctype="multipart/form-data"	: 必须,指定表单内容类型,支持文件上传;
	 -->  
	<form action="myupload" method="post" enctype="multipart/form-data">
	
		<p>	 <input type="text" name="name">	</p>		<!-- 模拟上传人 -->
		
		<p>  <input type="file" name="myfile">  </p>		<!-- 上传文件:用来上传文件的file组件 -->
			
		</p> <input type="submit" value="上传"> </p>			<!-- 提交 -->
	</form>
	
  </body>
</html>

  1. Write controller actions
	@RequestMapping("/myupload")
	public String myupload(String name,@RequestParam("myfile") MultipartFile myfile,HttpSession session) {
    
    
		/*	
		 * String name 									:页面给的用户名;
		 * @RequestParam("myfile") MultipartFile myfile :文件参数,@RequestParam 解决参数名不匹配,MultipartFile对象参数存储 上传文件的相关信息;
		 * HttpSession session 							:用于获取服务器 根路径;	
		 */
		if(!myfile.isEmpty()){
    
    							//判断 文件是否存在,不存在则不做文件上传操作;
			try {
    
    
				//获取上传路径: path
				//session.getServletContext() 获取服务器项目的根目录 .getRealPath("/myfile/"); 根目录下指定的文件,一般会在服务器中建一个文件专门存储上传的文件;
				String path = session.getServletContext().getRealPath("/myfile/");			//获取当前要上传服务器的路径;
				//上传的的文件名称: fileName
				String fileName = System.currentTimeMillis()+myfile.getOriginalFilename();					
				File updatefile = new File(path, fileName);									//IO文件操作,创建出对应的fileName文件名,放在对应的path目录下;
				//执行上传: 上面只是在指定目录下创建出了一个空的文件 updatefile; 但里面啥也没有;
				myfile.transferTo(updatefile);												//将数据存在 指定的文件中;
				
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		}
		return "ok";			//返回页面;
	}

	/*MultipartFile类型:
	 * 常用方法:
	 * 		isEmpty(); 	判断是否存在文件,true存在 false不存在		返回值 boolean
	 * 		getSize();	获取当前文件上传大小,可以进行对应验证;	 	返回值 long 即:文件的单位 字节; 1024字节=1kb 1024kb=1Mb..
	 * 		getOriginalFilename();	获取当前文件名,可用于获取文件后缀来来限制文件上传格式;  返回值 String
	 * 		transferTo(File);		参数文件类型,将指定的文件存在对应的 File 上;
	 * */
  1. The upload exception gives a reminder: the
    above example Demo did not write~

    General idea:
    a request is stored in the controller method. If an exception occurs during the upload process, an exception message is stored
    in the scope ; there is a hidden scope in the page form:
    <input type=“hidden” id=“xx” value ="${function to store exception information}" />
    After the page function(){} method page load event:
    $(function(){ //get the hidden form field object; .val() get its value; (el expression No data is null principle...) //Judgment value!=null then display data~! (The exception information is shown here) })



Multiple file upload:

Multi-file upload is relatively simple~ There are
not many code changes. Add a File to the form (after all, you need to upload one more file~) The
controller is slightly modified ~ Just modify it;

Form:

	<form action="myupload" method="post" enctype="multipart/form-data">
	
		<p>	 <input type="text" name="name">	</p>		<!-- 模拟上传人 -->
		
		<p>  <input type="file" name="myfile">  </p>		<!-- 上传文件:用来上传文件的file组件 -->
		
		<p>  <input type="file" name="myfile">  </p>		<!-- 上传文件:两个名字一样~ -->
			
		</p> <input type="submit" value="上传"> </p>			<!-- 提交 -->
	</form>

Controller:

	@RequestMapping("/myupload")
	public String myupload(String name,@RequestParam("myfile") MultipartFile myfiles[],HttpSession session) {
    
    	
		//参数 MultipartFile myfile 变为一个数组 myfiles[]
		
		//并使用 foreach 进行遍历~ ....就ok了我凑真简单~!
		for (MultipartFile myfile : myfiles) {
    
    
		if(!myfile.isEmpty()){
    
    							//判断 文件是否存在,不存在则不做文件上传操作;
			try {
    
    
				//获取上传路径: path
				//session.getServletContext() 获取服务器项目的根目录 .getRealPath("/myfile/"); 根目录下指定的文件,一般会在服务器中建一个文件专门存储上传的文件;
				String path = session.getServletContext().getRealPath("/myfile/");			//获取当前要上传服务器的路径;
				System.out.println(path);
				//上传的的文件名称: fileName
				String fileName = System.currentTimeMillis()+myfile.getOriginalFilename();					
				File updatefile = new File(path, fileName);									//IO文件操作,创建出对应的fileName文件名,放在对应的path目录下;
				//执行上传: 上面只是在指定目录下创建出了一个空的文件 updatefile; 但里面啥也没有;
				myfile.transferTo(updatefile);												//将数据存在 指定的文件中;
				
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		}
		
		}
		return "ok";			//返回页面;
	}
	
	//System.currentTimeMillis() 获得系统的时间,单位为毫秒; + myfile.getOriginalFilename(); 文件名; 
	//为了防止文件重名异常问题~

ok ~

Guess you like

Origin blog.csdn.net/qq_45542380/article/details/108694739