This article brings you the content is about spring boot how to achieve image upload and download (code), there is a certain reference value, the need for friends can refer to, I hope to help you.
1, the core controller code
Package Com.qwrt.station.websocket.controller;import Com.alibaba.fastjson.jsonobject;import Com.qwrt.station.common.util.jsonutil;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.value;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 Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import java.io.*;/** * Created by Jack on 2017/10/30. */@RestController @requestmapping ("V1/uploaddownload") public class Uploaddownloadcontroller {private static final Logger Logger = Loggerfactory.getlogger (Uploaddownloadcontroller.class); @Value ("${uploaddir}") Private String Uploaddir; @RequestMapping (value = "/uploadimage", method = REQUESTMETHOD.POST) public Jsonobject uploadimage (@RequestParam (value = "file") Multipartfile file) throws RuntimeException {I F (File.isempty ()) {return Jsonutil.getfailjsonobject ("File cannot be empty"); }//get filename String filename = file.getoriginalfilename (); Logger.info ("uploaded file name:" + fileName); Gets the suffix name of the file String suffixname = filename.substring (Filename.lastindexof (".")); Logger.info ("uploaded suffix named:" + Suffixname); File upload path after String filePath = Uploaddir; Solve Chinese problem, liunx Chinese path, picture display problem//FileName = Uuid.randomuuid () + suffixname; File Dest = new file (FilePath + fileName); Detects if there is a directory if (!dest.getparentfile (). exists ()) {Dest.getparentfile (). Mkdirs (); } try {File.transferto (dest); Logger.info ("File path after successful upload:" + FilePath + fileName); Return Jsonutil.getsuccessjsonobject (FileName); } catch (IllegalStateException e) {E.printstackTrace (); } catch (IOException e) {e.printstacktrace (); } return Jsonutil.getfailjsonobject ("File upload failed"); }//File download related code @RequestMapping (value = "/downloadimage", method = requestmethod.get) public String downloadimage (Str ing imagename,httpservletrequest request, httpservletresponse response) {//string fileName = "123.JPG"; Logger.debug ("The ImageName is:" +imagename); String fileUrl = uploaddir+imagename; if (FILEURL! = null) {//is currently getting the file from the web-inf//file//of the project (the directory can be configured in the following line of code) and then downloaded to c:\\users\\downloads, the default downloaded directory for this machine /* String Realpath = Request.getservletcontext (). Getrealpath ("//web-inf//"); *//*file File = new file (Realpath, fileName); */File File = new file (FILEURL); if (file.exists ()) {Response.setcontenttype ("application/force-download");//Set force download does not open resp Onse.addheader ("Content-disposition", "atTachment;filename= "+ imageName);//Set file name byte[] buffer = new byte[1024]; FileInputStream FIS = null; Bufferedinputstream bis = null; try {fis = new FileInputStream (file); bis = new Bufferedinputstream (FIS); OutputStream OS = Response.getoutputstream (); int i = bis.read (buffer); while (i! =-1) {os.write (buffer, 0, I); i = bis.read (buffer); } System.out.println ("Success"); } catch (Exception e) {e.printstacktrace (); } finally {if (bis! = null) {try {bis.close (); } catch (IOException e) {e.printstacktrace (); }} if (FIS! = null) {try {fis.close (); } catch (IOException e) {e.printstacktrace (); }}}}} return null; }}
The above code has two methods, the above method is the image upload method, the following method is the image download method. Download pictures need to pass in the file name of the picture, in ios,android phone, Google browser test, upload download no problem.
2, the core code of the test HTML is as follows, to upload and download pictures:
<! DOCTYPE html>
The above code is not related to the image upload and download, as needed to remove, see the image upload and download the core code, need to introduce jquery.
3,spring Boot's property configuration:
1, solve the picture upload too big problem:
Spring:http: multipart: max-file-size:100mb #文件上传大小 max-request-size:200mb #最打请求大小
Spring: http: multipart: max-file-size:100mb #文件上传大小 max-request-size:200mb # Maximum request size
This is the new spring boot resolution image or file upload too big problem, the boss does not solve this. You can check the information yourself.
2, the location where the profile upload is saved:
#上传位置
Uploaddir:f:\mystudy\pic\
Spring boot multiple file uploads:
Core code:
/** * Multiple file uploads * @param files * @return * @throws runtimeexception * * @RequestMapping (value = "/upload Files ", method = requestmethod.post) public jsonobject uploadfiles (@RequestParam (value =" file ") multipartfile[] files) {StringBuffer result = new StringBuffer (); try {for (int i = 0; i < files.length; i++) {if (files[i]! = NULL) {//Tune Using the Upload method String fileName = Executeupload (Files[i]); Result.append (filename+ ";");}} catch (Exception e) {e.printstacktrace (); Jsonutil.getfailjsonobject ("File upload failed"); } return Jsonutil.getsuccessjsonobject (Result.tostring ()); }/** * Extract upload Method for public method * @param file * @return * @throws Exception */private String Executeupload ( Multipartfile file) throws exception{//file suffix String suffix = file.getoriginalfilename (). substring (file.getOriginalFilename (). LastIndexOf (".")); Upload file name String filename = uuid.randomuuid () +suffix; The file object saved by the server is Serverfile = "New File" (Uploaddir + fileName); Detects if there is a directory if (!serverfile.getparentfile (). exists ()) {Serverfile.getparentfile (). Mkdirs (); }//Writes the uploaded file to the server-side file File.transferto (serverfile); return fileName; }