Fastdfs and Java integrated file upload download

Source: Internet
Author: User

Get ready
    1. Download fastdfs-client-java Source code

Source Address Password:s3sw

  1. Modifypom.xml
    The first plugins is required, is MAVEN used to compile the plug-in, the second is Maven hit the source package, you can not.

    <build><plugins>  <plugin>    <groupId>Org.apache.maven.plugins</groupId>    <artifactId>Maven-compiler-plugin</artifactId>    <version>3.5.1</version>    <configuration>      <encoding>UTF-8</encoding>      <source>${jdk.version}</source>      <target>${jdk.version}</target>    </configuration>  </plugin>  <plugin>      <groupId>Org.apache.maven.plugins</groupId>      <artifactId>Maven-source-plugin</artifactId>      <version>3.0.1</version>      <executions>          <execution>              <id>Attach-sources</id>              <goals>                  <goal>Jar</goal>              </goals>          </execution>      </executions>  </plugin></plugins></build>
  2. will be fastdfs-client-java packaged
    Direct Item Right-click, run as Maven install
    After the install succeeds, Fastdfs-client-java is successfully installed in the local repository.
    ---

    To write a tool class:
  • fdfs_client.confcopy the file into the resource of your project, modify it tracker.server , and don't move it:
  • Adding dependencies to the project pom.xml

    <dependency><groupId>org.csource</groupId><artifactId>fastdfs-client-java</artifactId><version>1.27-SNAPSHOT</version></dependency>
  • First of all to achieve file upload, fastdfs-client-java upload by passing in a byte[] to complete, a simple look at the source code:

    publicupload_file(byte[] file_buff, String file_ext_name,        throws IOException, MyException{finalnull;returnthis.upload_file0, file_buff.length, file_ext_name, meta_list);}
File properties
Package com.wuwii.utils;import java.io.Serializable;import java.util.Arrays;/*** @ClassName Fastdfsfile* @Description Fastdfs Upload file business object * @authorZhangkai* @date July 18, 2017 */ Public classFastdfsfileImplementsserializable{Private Static Final LongSerialversionuid = 2637755431406080379L;/*** file binary     */    Private byte[] content;/*** File name     */    PrivateString name;/*** File Length     */    PrivateLong size; Public Fastdfsfile(){            } Public Fastdfsfile(byte[] content, String name, Long size) { This.content= content; This.name= name; This.size= size; } Public byte[]getcontent() {returnContent } Public void setcontent(byte[] content) { This.content= content; } PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; } PublicLongGetSize() {returnSize } Public void setSize(Long size) { This.size= size; } Public Static Long Getserialversionuid() {returnSerialversionuid; }}
Writing the Fastdfs tool class
Package com.wuwii.utils;import java.io.Serializable;import org.apache.commons.io.FilenameUtils;import Org.csource.common.NameValuePair;import Org.csource.fastdfs.ClientGlobal;import org.csource.fastdfs.StorageClient1;import org.csource.fastdfs.TrackerClient;import Org.csource.fastdfs.TrackerServer;import Org.jetbrains.annotations.NotNull;import Org.springframework.core.io.ClassPathResource;import org.springframework.http.HttpHeaders;import Org.springframework.http.HttpStatus;import Org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;/*** @ClassName fastdfsutils* @Description Fastdfs Tool class * @authorZhangkai* @date July 18, 2017 */ Public classFastdfsutilsImplementsserializable{/**     *      */    Private Static Final LongSerialversionuid = -4462272673174266738l;Private StaticTrackerclient trackerclient;Private StaticTrackerserver Trackerserver;Private StaticStorageClient1 StorageClient1;Static{Try{//clientgloble Read configuration fileClasspathresource resource =New Classpathresource("fdfs_client.conf"); Clientglobal.Init(Resource.getClassLoader().GetResource("fdfs_client.conf").GetPath());//trackerclientTrackerclient =New trackerclient(); Trackerserver = trackerclient.getconnection();//storageclientStorageClient1 =New StorageClient1(Trackerserver,NULL); }Catch(Exception e) {e.Printstacktrace(); }    }/*** Fastdfs File Upload     * @param fileuploaded files Fastdfsfile     * @returnString returns the absolute path of the file     */     Public StaticStringUploadFile(Fastdfsfile file) {String Path =NULL;Try{//File name extensionString ext = filenameutils.getextension(file.GetName());//mata List is a description of the table filenamevaluepair[] Mata_list =Newnamevaluepair[3]; mata_list[0] =NewNamevaluepair ("FileName", file.GetName()); mata_list[1] =NewNamevaluepair ("Fileext", ext); mata_list[2] =NewNamevaluepair ("FileSize", String.valueOf(file.GetSize())); Path = StorageClient1.Upload_file1(file.getcontent(), ext, mata_list); }Catch(Exception e) {e.Printstacktrace(); }returnPath }/*** Fastdfs File Download     * @param groupNameGroup name     * @param remotefilenamefile name     * @param specfilenameReal file name     * @returnResponseentity<byte[]>     */@org. Jetbrains.annotations.NotNullPublic static responseentity<byte[]> downloadFile (String groupName, String remotefilename, String Specfilen AME) {byte[] content = null;httpheaders headers = new Httpheaders ();try {content = Storageclient1.download_file (GroupName, remotefilename);headers.setcontentdispositionformdata ("Attachment", New String (Specfilename.getbytes ("UTF-8"), "iso-8859-1 "));Headers.setcontenttype (mediatype.application_octet_stream);} catch (Exception e) {e.printstacktrace ();        }return new responseentity<byte[]> (content, headers, httpstatus.created);    }        /*** The group name of the file is obtained according to the path returned by Fastdfs* Path returned by @param path Fastdfs* @return     */Public static string Getgroupformfilepath (string path) {return Path.split ("/") [0];    }        /*** Get file name according to Path returned by Fastdfs* Path returned by @param path Fastdfs* @return     */@NotNullPublic static string Getfilenameformfilepath (string path) {return path.substring (Path.indexof ("/") +1);    }}
Test controller
Package Com.wuwii.controller;import java.io.IOException;import org.springframework.http.ResponseEntity;import Org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import Org.springframework.web.bind.annotation.RequestMethod;import Org.springframework.web.multipart.MultipartFile;import Com.wuwii.utils.FastDFSFile;import com.wuwii.utils.FastDFSUtils;import Com.wuwii.utils.PropertyUtil;/*** Fastfds Controller * @authorZhangkai * */@Controller@RequestMapping(Value ="/fastdfs") Public classFastfdscontroller {@RequestMapping(Value ="/upload", method = Requestmethod.POST) PublicStringUpload(Multipartfile file) {Try{Fastdfsfile Fastdfsfile =New Fastdfsfile(file.getBytes(), file.Getoriginalfilename(), file.GetSize()); String Path = fastdfsutils.UploadFile(Fastdfsfile);return "Redirect:"+ Propertyutil.Get("Fastfds_server") + path; }Catch(IOException e) {//TODO auto-generated catch blockE.Printstacktrace(); }return NULL; }@RequestMapping(Value ="/download") Publicresponseentity<byte[]>Download(string path, String specfilename) {String filename = fastdfsutils.Getfilenameformfilepath(path); String Group = fastdfsutils.Getgroupformfilepath(path);returnFastdfsutils.DownloadFile(group, filename, specfilename); }}
Finally, attach the tool class to read the configuration file Propertyutil
Package com.wuwii.utils;import Java.io.InputStream;import java.util.Properties;/*** @ClassName Propertyutil* @Description Read the contents of the configuration file (Key,value) * @authorZhangkai* @date July 18, 2017 */ Public classPropertyutil { Public Static FinalProperties PROP =NewProperties ();/** * @Method: Get* @Description: Read the contents of the configuration file (Key,value)     * @param key     * @returnString     * @throws     */     Public StaticStringGet(String key) {if(PROP.IsEmpty()) {Try{InputStream in = Propertyutil.class.getResourceAsStream("/config.properties"); PROP.Load(in); In.Close(); }Catch(Exception e) {}        }returnPROP.GetProperty(key); }}
Test upload!

Download

The download is simple because it is directly available to the binary stream and returned to the client.
Download the main point is to note that the file name returned from Fastdfs is such a random code, so we need to upload the name of the file itself to the database, and then to download the file header to reset the name.

Fastdfs and Java integrated file upload 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.