File upload of spring MVC

Keywords: Spring xml encoding JSP

Spring MVC provides direct support for file upload, which is implemented through plug and play MultipartResolver interface. Spring is implemented with its implementation class CommonsMultipartResolver.
There is no MultipartResolver in the context of spring MVC, so by default, spring MVC cannot handle the upload of files. If you need to use the upload function, you need to manually configure MultipartResolver.

Prepare jar package

Configure xml
<bean id="multipartResolver" 
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- Specify the default encoding format -->
	<property name="defaultEncoding" value="UTF-8" />
	<!-- Specify the file size allowed to upload, unit Byte-->
	<property name="maxUploadSize" value="512000" />
</bean>
Add jsp for uploading files
<form action="fileuploadpost" method="post" enctype="multipart/form-data">
			<input type="file" name="file"/>
			<input type="submit" value="upload"/>
		</form>
<img alt="Error" src="${imgurl}"/>	Upload successfully, jump back to display
Write receiving method
@RequestMapping(value ="/fileuploadpost" ,method = RequestMethod.POST)
	public String fileuploadpost(HttpServletRequest request,@RequestParam("file")MultipartFile file,Map<String,Object> map) {
		try {
			String fileName = getFileName(request,file);
			System.out.println(fileName);
			map.put("imgurl", fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "fileupload";
	}

public String getFileName(HttpServletRequest request,MultipartFile file) throws Exception, IOException {
		//Get upload path
		String path = request.getServletContext().getRealPath("uploads");
		System.out.println(path);
		
		//Get file path
		String filename = file.getOriginalFilename();
		String filsuffix= filename.substring(filename.lastIndexOf("."));
		System.out.println(filename);
		
		String newName = UUID.randomUUID()+filsuffix;
		
		File f = new File(path+"/"+newName);
		
		file.transferTo(f);
		
		return "uploads/"+newName;//Send picture path back
	}

MultipartFile can get the file fields submitted by the form
common method
isEmpty(): determine whether to submit a file
getContentType(): get file type
getName(): get form element name
getOriginalFilename(): get the submitted file name
getInputStream(): get file stream
getSize(): get file size
getBytes(): get byte array

Posted by CONFUSIONUK on Wed, 16 Oct 2019 09:24:55 -0700