This article describes how to upload a file using spring boot, which we show you how to upload files to the Distributed File system Fastdfs using spring boot.
This project will be built on the basis of the previous project.
1, POM package configuration
We use the latest version of Spring boot 1.5.9, JDK use 1.8, tomcat8.0.
<< Span class= "Hljs-name" >dependency> < Groupid>org.csource</groupId> <artifactid>fastdfs-client-java </artifactid> <version>1.27-snapshot</< Span class= "Hljs-name" >version></ Dependency>
Added a fastdfs-client-java
package to invoke the Fastdfs related API.
2. Configuration files
Add files under Resources directory fdfs_client.conf
60network_timeout = 60charset = UTF-8http.tracker_http_port = 8080http.anti_steal_token = nohttp.secret_key = 123456tracker_server = 192.168.53.85:22122tracker_server = 192.168.53.86:22122
The configuration file sets the timeout period for the connection, the encoding format, and the Tracker_server address.
More information: Fastdfs-client-java
3. Package Fastdfs Upload Tool class
Package Fastdfsfile, file base information includes file name, content, file type, author, and so on.
public class FastDFSFile { private String name; private byte[] content; private String ext; private String md5; private String author; //省略getter、setter
Encapsulates the Fastdfsclient class, including common upload, download, delete and other methods.
The
First reads the corresponding configuration information and initializes it when the class loads.
static {try {String FilePath = new class Pathresource ( "fdfs_client.conf"). getabsolutepath (); Clientglobal. init (filePath); trackerclient = new getconnection (); storageserver = Trackerclient. getstorestorage (trackerserver);} catch (Exception e) {logger. "Fastdfs Client Init fail!", e);}}
File Upload
PublicStatic string[]Upload (fastdfsfile file) {logger.Info"File Name:" + file.GetName () +"File Length:" + file.GetContent ().length); namevaluepair[] Meta_list =New namevaluepair[1]; meta_list[0] =New Namevaluepair ("Author", file.Getauthor ());Long startTime = System.Currenttimemillis (); string[] Uploadresults =Nulltry {storageclient =NewStorageclient (Trackerserver, storageserver); Uploadresults = storageclient.Upload_file (file.GetContent (), file.Getext (), meta_list); }catch (IOException e) {logger.Error"IO Exception when uploadind the file:" + file.GetName (), E); }catch (Exception e) {logger.Error"Non IO Exception when uploadind the file:" + file.GetName (), E); } logger.Info"Upload_file time used:" + (System.Currenttimemillis ()-startTime) +"MS");if (uploadresults = null ) {logger. error ( "Upload file fail, error code:" + storageclient.< Span class= "Fu" >geterrorcode ()); } String groupName = Uploadresults[0]; String remotefilename = Uploadresults[1]; Logger. "Upload file successfully!!!" + " group_name: "+ groupName + return uploadresults;}
Use the client storageclient provided by Fastdfs to upload the file, and finally return the upload results.
Get file information based on groupname and file name.
Public StaticFileInfoGetFile(String groupName, String remotefilename) {try {storageclient = new storageclient (Trackerserver, storageserver); return storageclient. Get_file_info (GroupName, remotefilename);} catch (IOException e) {logger. Error ("IO exception:get File from Fast DFS failed", e);} catch (Exception e) {logger. Error ("Non IO exception:get File from Fast DFS failed", e);} return null;}
Download file
Public StaticInputStreamDownfile(String groupName, String remotefilename) {try {storageclient =Newstorageclient (Trackerserver, storageserver); byte[] filebyte = Storageclient.new Bytearrayinputstream (Filebyte); return ins;} catch (IOException e) {logger. "IO exception:get File from Fast DFS failed", e);} catch (Exception e) {logger. "Non IO exception:get File from Fast DFS failed", e);} return null;}
deleting files
Public static < Span class= "Hljs-keyword" >void deletefile (string groupName, String Remotefilename) throws Exception {storageclient = new int i = Storageclient.info ( "delete file successfully!!!" + i);}
When using Fastdfs, call the fastdfsclient corresponding method directly.
4, write the Upload control class
Read the file information from the Multipartfile, and then use Fastdfsclient to upload the file to the Fastdfs cluster.
PublicStringSaveFile(Multipartfile multipartfile)ThrowsIOException {string[] fileabsolutepath={}; String Filename=multipartfile.Getoriginalfilename (); String ext = fileName.SUBSTRING (fileName.LastIndexOf (".") +1);byte[] File_buff =Null InputStream Inputstream=multipartfile.getInputStream ();if (inputstream!=NULL) {int len1 = InputStream.Available (); File_buff =NewBYTE[LEN1]; InputStream.Read (File_buff); } inputstream.Close (); Fastdfsfile file =NewFastdfsfile (FileName, File_buff, ext);try {Fileabsolutepath = fastdfsclient. upload (file); //upload to Fastdfs} catch (Exception e) {logger. "Upload file exception!", e);} if (fileabsolutepath== NULL) {Logger. "Upload file Failed,please upload again!");} String path=fastdfsclient. gettrackerurl () +fileabsolutepath[0]+ 1]; return Path;}
Request control, call the above method saveFile()
.
@PostMapping ("/upload")new annotation since 4.3PublicStringSinglefileupload(@RequestParam("File") multipartfile file, Redirectattributes redirectattributes) {if (file.IsEmpty ()) {redirectattributes.Addflashattribute ("Message","Select a file to upload");Return"Redirect:uploadstatus"; }try {Get the file and save it somewhere String path=savefile (file); redirectattributes. addflashattribute ( "message", "You successfully uploaded '" + file. getoriginalfilename () + "'"); Redirectattributes. addflashattribute ( "path", "file path URL '" + Path + "'");} catch (Exception e) {logger. "Upload file failed", e);} return "redirect:/ Uploadstatus ";}
After the upload succeeds, the path of the file is displayed to the page as follows:
Access to this URL in the browser, you can see the success through the Fastdfs show
This is done using the Spring Boot integrated Fastdfs case.
Sample Code-github
Spring Boot (18) Integrated Fastdfs file upload download