Springboot-17-springboot File Upload and download

Source: Internet
Author: User

Single File Upload

1, you need to use Thymeleaf Template: http://www.cnblogs.com/wenbronk/p/6565834.html

Src/main/resource/template/file.html

<! DOCTYPE html>"http://www.w3.org/1999/xhtml"Xmlns:th="http://www.thymeleaf.org"xmlns:sec="Http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> "POST"Enctype="Multipart/form-data"action="/upload"> <p> files: <input type="file"Name="file"/></p> <p><input type="Submit"Value="Upload"/></p> </form> </body>

File Upload Method

Package Com.iwhere.main.controller;import Java.io.bufferedinputstream;import java.io.BufferedOutputStream; Import Java.io.file;import java.io.fileinputstream;import Java.io.ioexception;import Java.util.List;import Java.util.uuid;import Javax.servlet.servletoutputstream;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.bind.annotation.restcontroller;import Org.springframework.web.multipart.MultipartFile; Import Org.springframework.web.multipart.MultipartHttpServletRequest;/** * File Upload controller * * @RestController equivalent to simultaneous @Controller and @responsebody two annotations * * @author Wenbronk * @time April 6, 2017 pm 2:43:03*/@RestController Public classFileuploadcontroller {/** * File Upload * * @return*/@RequestMapping (Value="/upload", method =requestmethod.post) PublicString Handlfileupload (@RequestParam ("file") multipartfile file) {if(File.isempty ()) {return "the file is empty"; }        //reads the contents of the file and writes it to the specified directoryString FileName =File.getoriginalfilename (); //String suffixname = filename.substring (Filename.lastindexof ("."));FileName = Uuid.randomuuid () +"|+=|-|"+FileName; File dest=NewFile ("e:/test/"+fileName); //determine if a directory exists        if(!Dest.getparentfile (). exists ())        {Dest.getparentfile (). Mkdirs (); }        Try{File.transferto (dest); } Catch(IOException e) {return "backstage also don't know why, anyway is upload failed"; }        return "Upload Successful"; }}
Multiple file uploads:

1, Thymeleaf

Src/main/resource/template/multifile.html

<! DOCTYPE html>"http://www.w3.org/1999/xhtml"Xmlns:th="http://www.thymeleaf.org"xmlns:sec="Http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> "POST"Enctype="Multipart/form-data"action="/batch/upload"> <p> Files 1:<input type="file"Name="file"/></p> <p> file 2:<input type="file"Name="file"/></p> <p> file 3:<input type="file"Name="file"/></p> <p><input type="Submit"Value="Upload"/></p> </form> </body>

2, multi-File Upload method

    /** * Multi-File Upload * Similar to single file upload, traverse * @return*/@RequestMapping (Value="Multiupload", method =requestmethod.post) PublicString handlemultifileupload (httpservletrequest request) {List<MultipartFile> files = ((multiparthttpservletrequest) request). GetFiles ("file");  for(Multipartfile multipartfile:files) {if(Multipartfile.isempty ()) {return "the file is empty"; }            //reads the contents of the file and writes it to the specified directoryString FileName =Multipartfile.getoriginalfilename (); //String suffixname =//filename.substring (Filename.lastindexof ("."));FileName = Uuid.randomuuid () +"|+=|-|"+FileName; File dest=NewFile ("e:/test/"+fileName); //determine if a directory exists            if(!Dest.getparentfile (). exists ())            {Dest.getparentfile (). Mkdirs (); }            Try{Multipartfile.transferto (dest); } Catch(IOException e) {return "backstage also don't know why, anyway is upload failed"; }        }        return "Upload Successful"; }
File download
/** * File Download * * @return*/@RequestMapping ("/download")     PublicString DownLoadFile (httpservletrequest request, httpservletresponse response) {//The file name can be obtained from the request, here for convenience, written deadString FileName ="Rtsch_ex.json"; //String Path = Request.getservletcontext (). Getrealpath ("/");String Path ="e:/test"; File File=NewFile (path, fileName); if(File.exists ()) {//set force download to openResponse.setcontenttype ("Application/force-download"); //garbled file name, using new String () to reverse encodeResponse.AddHeader ("content-disposition","attachment;filename="+fileName); //Read FileBufferedinputstream bi =NULL; Try {                byte[] buffer =New byte[1024x768]; Bi=NewBufferedinputstream (NewFileInputStream (NewFile (""))); Servletoutputstream OutputStream=Response.getoutputstream (); inti =-1;  while(-1! = (i =bi.read (buffer))) {outputstream.write (buffer,0, i); }                return "Download Successful"; } Catch(Exception e) {return "Program Ape really don't know why, anyway, download failed."; } finally {                if(Bi! =NULL) {                    Try{bi.close (); } Catch(IOException e) {e.printstacktrace (); }                }            }        }        return "file does not exist"; }

File download, the most likely to appear garbled file name problem, here using new String () to deserialize,

String downname = new String (Filename.getbytes ("GBK"), "iso8859-1");

There is, of course, a less stable approach:

" UTF-8 "));  

There's another kind of, not very effective.

Springboot-17-springboot 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.