Java uploads image files to the server, including single file and multiple files, compatible with IE8, 9

About the project:
    The backend adopts the SpringMVC framework, and the frontend uses jQuery-1.9.1-min.js and jquery.form.js, which can meet the requirements of uploading multiple text content and multiple files at the same time. The upload speed is fast, and it is compatible with IE8 and 9 , Chrome and other mainstream browsers.

Requirement background:
   Multiple product records need to be uploaded, and each record contains multiple text descriptions and an image file.

In the early stage
   , there are two methods for uploading pictures to the server.
   One is to convert the picture into a Base64 string, and pass it to the background together with the text information in the form of json, and the background parses and saves the picture.
   2. Using MultipartFile to upload multiple files
   is obvious. After converting to Base64, the size of the image will become larger. When uploading multiple images, the speed is particularly slow. Therefore, what is described here is to use MultipartFile to realize multiple file uploads.
   But no matter which method is used to upload pictures, we always save the pictures in the specified path of the server, and finally save the path of the picture file in the database, not the picture itself.

1. Front-end implementation

1. Upload with FormData (not compatible with IE8)

<form id="uploadForm" method="post" enctype="multipart/form-data”>
<table>
<tr>
	    <input type="text" id="text1" name="text"/>
		<input type="file" id="file1" name="file"/>
	    <input type="text" id="text2" name="text"/>
		<input type="file" id="file2" name="file"/>
	    <input type="text" id="text3" name="text"/>
		<input type="file" id="file3" name="file"/> 
	  	<input type="button" id="submit" value="上传" onclick="uploadSubmit()">
</tr>
 </table>
</form>
<script>
	function uploadSubmit(){
    
    
  		var formData = new FormData(document.getElementById('uploadForm'));
  		$.ajax({
    
    
  			url:"uploadFiles",
  			type:"post",
  			data:formData,
  			dataType:"json",
  			processData:false,//必须要写
  			contentType:false,//必须要写
  			success:function(result){
    
    
  				console.log(result);
  			}
  		});
	}
</script>

    Here is an example of a text box corresponding to an image file, which can be changed according to actual needs. When there are multiple files, it is recommended that the name attribute be the same, and the backend can obtain the file list according to the same name attribute

Note:
    1. new FormData(document.getElementById('uploadForm') ) cannot be written as new FormData($(“#uploadForm”)), jQuery and native nodes differ in this.
    2. When uploading by ajax: be sure to set processData: false, contentType: false, otherwise an error will be reported: Illegal invocation

2. Upload with ajaxSubmit of jquery.form.js (compatible with IE8)

    Since the FormData+ajax method is not compatible with IE8, the jquery.form method is used. You only need to modify the uploadSubmit() method after introducing the jquery.form.js file

function uploadSubmit(){
    
    
	$("#uploadForm").ajaxSubmit({
    
    
	  	url:"uploadFiles",
	  	type:"post",
	  	dataType:"json",
	  	async:false,
	  	success:function(result){
    
    
	  		console.info(result);
	  	}
	  });
 }

    But when using ajaxSubmit to upload files and return json data in the background, IE8 will prompt to download the json file.
    Solution: The backend does not return 'application/json' type data, but instead returns 'text/html' type to the frontend. Pay attention to remove the 'dataType:json' attribute of ajax.

Second, the back-end implementation

    To use MultipartFile in the backend, commons-io.jar and commons-fileupload.jar dependencies need to be added, otherwise the value is null
    and registered in the applicationContext.xml file:

<!-- ======================注册文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 文件上传大小限制 -->
	<property name="maxUploadSize">
		<value>10485760</value>
	</property>
	<property name="defaultEncoding">
		<value>UTF-8</value>
	</property>
</bean>

1. Single file upload

@ResponseBody
@RequestMapping("/uploadFiles")
public String uploadFiles(MultipartFile file,String text,HttpServletRequest request){
    
    
	try {
    
    
		//图片保存路径:/tomcat/webapps/项目名/
		String 	sysPath=request.getSession().getServletContext().getRealPath("");
		if(file!=null){
    
    
				//此处是将文本+图片原文件名作为图片的新文件名
				String fileName=text+file.getOriginalFilename();
				File filePath=new File(sysPath,fileName);
				if(!filePath.getParentFile().exists()){
    
    
					filePath.getParentFile().mkdirs();
				}
				//System.out.println("文件名:"+fileName+" ----- "+filePath.getPath());
				BufferedOutputStream out=new BufferedOutputStream(new 	FileOutputStream(filePath));
				out.write(image.getBytes());
				out.flush();
				out.close();
		}else{
    
    
			return "no file";
		}
	} catch (FileNotFoundException e) {
    
    
		
	}catch(IOException e){
    
    
		
	}
	return "success";
}

2. Multiple file upload

@ResponseBody
@RequestMapping("/uploadFiles")
public String uploadFiles(MultipartFile[] file,String[] text,HttpServletRequest request){
    
    
	try {
    
    
		//图片保存路径:/tomcat/webapps/项目名/
		String 	sysPath=request.getSession().getServletContext().getRealPath("");
		if(file!=null&&file.length>0){
    
    
			for(int i=0;i<file.length;i++){
    
    
				MultipartFile image=file[i];
				//此处是将文本+图片原文件名作为图片的新文件名
				String fileName=text[i]+image.getOriginalFilename();
				File filePath=new File(sysPath,fileName);
				if(!filePath.getParentFile().exists()){
    
    
					filePath.getParentFile().mkdirs();
				}
				System.out.println("文件名:"+fileName+" ----- "+filePath.getPath());
				BufferedOutputStream out=new BufferedOutputStream(new 	FileOutputStream(filePath));
				out.write(image.getBytes());
				out.flush();
				out.close();
			}
		}else{
    
    
			return "failure";
		}
	} catch (FileNotFoundException e) {
    
    
		
	}catch(IOException e){
    
    
		
	}
	return "success";
}

Note:
    1. According to the above file saving path: /tomcat/webapps/project name/test.jsp, then when the tomcat server restarts, the picture will be cleared. Because tomcat restart will redeploy the application. Therefore, it is recommended to change the file save path.
    2. When the front end does not select a file (that is, an empty file), IE8 and 9 receive data in the background and behave differently from other browsers such as chrome and IE11. Empty files will be included in the number, and other browsers will only accept non-empty files. document.
    Therefore, the background uses multipartFile.isEmpty( ) to determine whether the file is empty.

    Since then, the file upload module has ended. I have gone through many detours. In order to be compatible with IE8, I considered using base64 to upload files, but the speed is very slow. But it can be regarded as gaining wisdom through a fall in the pit. How to upload pictures with base64, please post it when you have time~

Guess you like

Origin blog.csdn.net/qq_38118138/article/details/118088539