Spring boot Get started--File upload and download

Source: Internet
Author: User
Tags file copy save file

Spring Boot Get started--File upload and download
Https://www.cnblogs.com/studyDetail/p/7003253.html1, adding dependent replication code to the Pom.xml file<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelversion>4.0.0 </modelVersion> <groupId>com.wyl</groupId> <artifactId>SpringBootFile</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springbootfile </name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.versi on>1.7</java.version> </properties> <parent> <groupid>org.springframework.boot</gro Upid> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.release</ version> </parent> <dependencies> <dependency> <groupId>junit</groupId> &L T;artifactid>junit</artifactid> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <a Rtifactid>spring-boot-starter-web</artifactid> </dependency> <!--thymeleaf Templates plug-in--< Dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter -thymeleaf</artifactid> </dependency> <!--devtools plug-in, hot deploy-<dependency> <groupid>org.springframework.bo Ot</groupid> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> </dependencies></project>Copy Code2, the template file cache is canceled in the application.properties file Spring.thymeleaf.cache=false3, writing template file copy code file.html<! DOCTYPE html>xmlns:sec= "Http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" >multifile.html<! DOCTYPE html>xmlns:sec= "Http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" >Copy Code4, write controller copy codeImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.bind.annotation.ResponseBody;Importorg.springframework.web.multipart.MultipartFile; @Controller Public classFileuploadcontroller {/** Get file.html page*/@RequestMapping ("File") PublicString file () {return"/file"; } /*** Implement file Upload **/@RequestMapping ("FileUpload") @ResponseBody PublicString FileUpload (@RequestParam ("FileName") multipartfile file) {if(File.isempty ()) {return"False"; } String fileName=File.getoriginalfilename (); intSize = (int) file.getsize (); System.out.println (FileName+ "-+" +size); String Path= "F:/test" ; File dest=NewFile (path + "/" +fileName); if(!dest.getparentfile (). exists ()) {//determine if the file parent directory existsdest.getparentfile (). mkdir (); } Try{File.transferto (dest);//Save File return"True"; } Catch(IllegalStateException e) {//TODO auto-generated Catch blockE.printstacktrace (); return"False"; } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); return"False"; }}/** Get multifile.html page*/@RequestMapping ("Multifile") PublicString multifile () {return"/multifile"; } /*** Implement multi-File upload **/@RequestMapping (Value= "Multifileupload", method=requestmethod.post)/**Public @ResponseBody String multifileupload (@RequestParam ("FileName") list<multipartfile> files)*/ Public@ResponseBody String multifileupload (httpservletrequest request) {List<MultipartFile> files = ((multiparthttpservletrequest) request). GetFiles ("FileName"); if(Files.isempty ()) {return"False"; } String Path= "F:/test" ; for(Multipartfile file:files) {String fileName=File.getoriginalfilename (); intSize = (int) file.getsize (); System.out.println (FileName+ "-+" +size); if(File.isempty ()) {return"False"; }Else{File dest=NewFile (path + "/" +fileName); if(!dest.getparentfile (). exists ()) {//determine if the file parent directory existsdest.getparentfile (). mkdir (); } Try{File.transferto (dest); }Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); return"False"; } } } return"True"; }} Copy Code5, Test

6, multi-File upload problems encountered org.apache.tomcat.util.http.fileupload.fileuploadbase$filesizelimitexceededexception:the field FileName exceeds its maximum permitted size of1048576bytes.  Spring boot default file upload size is 2M, multiple document uploads always appear in file size out of bounds solution: A, set the file size in the Application.properties file # single, max size Multipart.maxfilesize=50mb# All files max size multipart.maxrequestsize=50Mb However, it turns out that this method is not able to solve the above problem B, configure the Bean in the Startup class App.class file to set the file size copy codeImportjavax.servlet.MultipartConfigElement;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.boot.web.servlet.MultipartConfigFactory;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;/*** Hello world! **/@SpringBootApplication @configuration Public classApp { Public Static voidMain (string[] args) {System.out.println ("Hello world!" ); Springapplication.run (App.class, args); }        /*** File Upload configuration *@return       */@Bean Publicmultipartconfigelement multipartconfigelement () {Multipartconfigfactory factory=Newmultipartconfigfactory (); //Single File MaxFactory.setmaxfilesize ("10240KB");//KB,MB        ///Set Total upload data total sizeFactory.setmaxrequestsize ("102400KB"); returnFactory.createmultipartconfig (); Copy the Code7, File download copy code @requestmapping ("Download")     Publicstring DownLoad (HttpServletResponse response) {string filename= "2.jpg"; String FilePath= "F:/test" ; File File=NewFile (FilePath + "/" +filename); if(File.exists ()) {//determine if the file parent directory existsResponse.setcontenttype ("Application/force-download"); Response.setheader ("Content-disposition", "attachment;filename=" +filename); byte[] buffer =New byte[1024]; FileInputStream FIS=NULL;//file input streamBufferedinputstream bis =NULL; OutputStream OS=NULL;//output Stream            Try{OS=Response.getoutputstream (); FIS=Newfileinputstream (file); Bis=NewBufferedinputstream (FIS); inti =bis.read (buffer);  while(I! =-1) {os.write (buffer); I=bis.read (buffer); }                            } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("----------File Download" +filename); Try{bis.close ();            Fis.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }        return NULL; }

Spring boot Get started--File upload and download

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.