Springboot Upload File

Source: Internet
Author: User
Tags uuid

Configure the upload path and file limit size in the application.yml configuration file

Spring:
   servlet:
      multipart:
        max-file-size:10kb 
Upload:
   file:
      location:d:\upload\

officially available configurable items:

# MULTIPART (multipartproperties)
Spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads. Spring.servlet.multipart.file-size-threshold=0 # threshold after which files are written to disk.
Values can use the suffixes ' MB ' or ' KB ' to indicate megabytes or kilobytes, respectively.
Spring.servlet.multipart.location= # Intermediate location of uploaded files. SPRING.SERVLET.MULTIPART.MAX-FILE-SIZE=1MB # max file size.
Values can use the suffixes ' MB ' or ' KB ' to indicate megabytes or kilobytes, respectively. SPRING.SERVLET.MULTIPART.MAX-REQUEST-SIZE=10MB # Max request size.
Values can use the suffixes ' MB ' or ' KB ' to indicate megabytes or kilobytes, respectively. Spring.servlet.multipart.resolve-lazily=false # Whether To resolve the multipart request lazily at the time of file or par
Ameter access. 
Official website Path: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/# Howto-multipart-file-upload-configuration

Create an upload request controller

first, use the @value annotation in controller to get the save path to the uploaded file

@Value ("${upload.file.location}")
private String uploadlocation;

Then write the request method

 @PostMapping (value = "/upload") public responseentity<?> upload (httpservletrequest reqquest, @RequestParam ("fil E ") multipartfile file {try {if (File.isempty ()) {return new responseentity<string> (" File is empty ", Httpstatu
		     s.accepted);
			}//string Uploaddir = Resourceutils.geturl ("classpath:"). GetPath ();
			String Uploaddir = Reqquest.getsession (). Getservletcontext (). Getrealpath ("/") + "upload\\";
			String uploaddir = uploadlocation;
			File dir = new file (Uploaddir);
			if (!dir.exists ()) {dir.mkdirs ();
			String filename = File.getoriginalfilename ();
			File Serverfile = new file (uploaddir + filename);
			File.transferto (Serverfile);
		return new Responseentity<string> ("Upload success", Httpstatus.ok);
			catch (IllegalStateException e) {e.printstacktrace ();
		return new responseentity<string> ("Upload failed", httpstatus.accepted);
			catch (IOException e) {e.printstacktrace (); return new responseentity<string> ("Upload failed", Httpstatus.)accepted); }
	}
One thing to note here is that file in @requestparam ("file") must match the name attribute of the HTML upload input, such as

<form action= "Upload" method= "post" enctype= "Multipart/form-data" >
        <p> Select File: <input type= "File" Name= "File"/></p>
        <p><input type= "Submit" value= "submitted"/></p>
</form>
If you need to customize the saved file name, add the following code:

String suffix = filename.substring (Filename.lastindexof ("."));
String definename = uuid.randomuuid () + suffix;

Upload Multiple Files
    @PostMapping (value = "/uploads") public responseentity<?> uploads (HttpServletRequest reqquest, @RequestParam ("File")
		Multipartfile[] files) {//string Uploaddir = Resourceutils.geturl ("classpath:"). GetPath ();
		String Uploaddir = Reqquest.getsession (). Getservletcontext (). Getrealpath ("/") + "upload\\";
		String uploaddir = uploadlocation;
		File dir = new file (Uploaddir);
		if (!dir.exists ()) {dir.mkdirs ();
				for (int i=0;i<files.length;i++) {if (files[i]!= null) {Multipartfile file = Files[i];
				String filename = File.getoriginalfilename ();
				String suffix = filename.substring (Filename.lastindexof ("."));
				String definename = uuid.randomuuid () + suffix;
				File Serverfile = new file (Uploaddir + definename);
				try {File.transferto (serverfile);
					catch (IllegalStateException e) {e.printstacktrace ();
				return new responseentity<string> ("Upload the first" +i+ "File Failure", httpstatus.accepted); catch (IOException e) {E.printstaCktrace ();
				return new responseentity<string> ("Upload the first" +i+ "File Failure", httpstatus.accepted);		
	}} return new Responseentity<string> ("Upload succeeded", Httpstatus.ok); }



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.