1. Import Upload Download dependency:
<dependency> <groupId>commons-fileupload</groupId> <artifactid>commons-fileu pload</artifactid> <version>1.3.2</version> </dependency> <dependency& Gt <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <versio N>2.4</version> </dependency>
<!--add Thymeleaf
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-thymeleaf</artifactid>
</dependency>
2. Upload:
1) front page:
<!DOCTYPE HTML><HTMLLang= "en"xmlns:th= "http://www.w3.org/1999/xhtml"><Head> <MetaCharSet= "UTF-8"> <title>Title</title> <Script> functionExproexcel () {}</Script></Head><Body> <H1>Spring Boot</H1> <ahref= "/expro/excel">Export</a> <PTh:text= "${hello}"></P> <P>File Upload</P> <formAction= "/upload/file"Method= "POST"enctype= "Multipart/form-data">Upload:<inputtype= "File"name= "Upfile"/> <Buttontype= "Submit">Submit</Button> </form></Body></HTML>
2) write the skip to upload page interface:
@Controller Public class Hellocontroller { @RequestMapping ("/hello") public String helloindex (HashMap <string, object> map) { map.put ("Hello", "Hello springboot!" ); return "/index"; }}
3) write the Receive upload file interface:
@Controller @requestmapping ("/upload") Public classUploadfilecontroller {@RequestMapping (value= "/file") Public@ResponseBody String UploadFile (@RequestParam ("Upfile") multipartfile file, HttpServletRequest request) {String message=""; Try { if(!File.isempty ()) {FileOutputStream OutputStream=NewFileOutputStream ("F:\\xiaoyao" + "\ \" +file.getoriginalfilename ()); Outputstream.write (File.getbytes ()); Outputstream.flush (); Outputstream.close (); Message= "Upload succeeded!" "; } } Catch(unsupportedencodingexception e) {e.printstacktrace (); Message= "Upload failed!" "; } Catch(IOException e) {e.printstacktrace (); Message= "Upload failed!" "; } returnmessage; }}
3. Download:
1) write the Download interface:
@RestController @requestmapping ("/expro") Public classExprotexcelcontroller {@RequestMapping ("/excel") Public voidExproexcel (HttpServletRequest request, httpservletresponse response)throwsexception{String Path= Classloader.getsystemresource (""). Touri (). GetPath ();//Get class Load addressSystem.out.println (path); File File=NewFile (path+ "exceltempalte/template. xlsx"); FileInputStream FileInputStream=NewFileInputStream (file);//Read FileResponse.setheader ("Content-disposition", "attachment;filename=test.xlsx");//set the response header and file nameOutputStream OutputStream =Response.getoutputstream (); //Create buffers byte[] Buffe =New byte[1024]; intLen =0; while(Len =fileinputstream.read (buffe)) >0) {outputstream.write (Buffe,0, Len); } fileinputstream.close (); Outputstream.flush (); Outputstream.close (); }}
Springboot Easy Upload Download