SPRINGMVC Integration Fastdfs-client-java Implement Web file upload download __web

Source: Internet
Author: User
Preface

The previous blog recorded the installation and configuration of Fastdfs v5.0.5 in Linux CentOS 7 (Distributed File System Fastdfs 5.0.5 & Linux CentOS 7 installation configuration), This blog mainly records SPRINGMVC integration Fastdfs Java Client to implement the Web file upload and download. Download Compilation

On the larger github can download to the source code of Fastdfs-client-java:

As shown above, this version is compiled by JDK1.5, according to the requirements of the source can recompile the jar package, I will be the original project's version of the Maven compiled plug-ins to JDK 1.7 after the compilation, After the compilation is successful, you can see the Fastdfs-client-java jar package at our local maven warehouse:

Finally, add the Fastdfs-client-java coordinate information to the Pom of our project to be OK:

<!--fastdfs-client-->
<dependency>
    <groupId>org.csource</groupId>
    < artifactid>fastdfs-client-java</artifactid>
    <version>1.25</version>
</ Dependency>
File Upload

First to achieve file upload, Fastdfs-client-java upload is through a byte[] to complete, a simple look at the source:

Public string[] Upload_file (byte[] file_buff, String file_ext_name, 
           namevaluepair[] meta_list) throws IOException, myexception{
    final String group_name = null;
    Return This.upload_file (group_name, File_buff, 0, File_buff.length, File_ext_name, meta_list);

As shown above, for the moment no longer in-depth study of the principle, here we know that we need a byte[] type of parameters can be, and Springmvc file upload Multipartfile object can be directly through the GetBytes method to get file byte[], That is, the GetBytes in the Commonsmultipartfile class (), the source code is as follows:

@Override public
byte[] GetBytes () {
    if (!isavailable ()) {
        throw new IllegalStateException ("File has been Moved-cannot be read Again ");
    }
    byte[] bytes = This.fileItem.get ();
    Return (bytes!= null bytes:new byte[0]);
}

Then we will know how to upload, of course, first of all need to do some simple encapsulation, here the file upload related attributes encapsulated in an interface, need to use the file upload related entities or tools to directly implement this interface can be:

Public interface Filemanagerconfig extends Serializable {public

    static final String File_default_author = "Wangliang ";

    public static final String PROTOCOL = "http://";

    public static final String SEPARATOR = "/";

    public static final String tracker_ngnix_addr = "192.168.0.68";

    public static final String tracker_ngnix_port = "";

    public static final String client_config_file = "fdfs_client.conf";
}

Next define the entity classes for the Fastdfs file:

Package Com.wl.bean; /** * <strong> class Profile: Fastdfs file entity </strong> <br> * <strong> Date Created: 2016-9-27 pm 10:29:25</strong& Gt <br> * * @Project springmvc-main (com.wl.bean) * @author Wang Liang * @version 1.0.0/public class Fastdfsfil

    E implements Filemanagerconfig {private static final long serialversionuid = 1L;
    Private byte[] content;
    private String name;
    Private String ext;
    private String length;

    Private String author = file_default_author;
        Public Fastdfsfile (byte[] content, String ext) {this.content = content;
    This.ext = ext;
        Public Fastdfsfile (byte[] content, string name, String ext) {this.content = content;
        THIS.name = name;
    This.ext = ext; Public Fastdfsfile (byte[] content, string name, string ext, string length, string author) {Thi
        s.content = content;
        THIS.name = name;
        This.ext = ext; this.length = length;
        This.author = author;
    Byte[] GetContent () {return content;
    public void SetContent (byte[] content) {this.content = content;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public String Getext () {return ext;
    public void Setext (String ext) {this.ext = ext;
    Public String GetLength () {return length;
    public void SetLength (String length) {this.length = length;
    Public String Getauthor () {return author;
    } public void Setauthor (String author) {this.author = author;
 }

}

The

, as shown above, includes the File_buff and file_ext_name necessary for uploading and several file description attributes that are stored in meta_list. Next look at the core tool class FileManager:

Import Java.io.File;

Import java.io.IOException;
Import Org.csource.common.NameValuePair;
Import Org.csource.fastdfs.ClientGlobal;
Import org.csource.fastdfs.StorageClient;
Import Org.csource.fastdfs.StorageServer;
Import org.csource.fastdfs.TrackerClient;
Import Org.csource.fastdfs.TrackerServer;
Import Org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.http.MediaType;

Import org.springframework.http.ResponseEntity; /** * <strong> class overview: Fastdfs Java Client Tool class </strong> <br> * <strong> Date Created: 2016-9-26 morning 10:26:48</st Rong> <br> * * @Project springmvc-main (com.wl.bean) * @author Wang Liang * @version 1.0.0/public class F
    Ilemanager implements Filemanagerconfig {private static final long serialversionuid = 1L;
    private static trackerclient trackerclient;
    private static Trackerserver Trackerserver;
    private static Storageserver Storageserver; private static Storageclient StoRageclient; static {try {String ClassPath = new File (FileManager.class.getResource ("/"). GetFile ()). Getcanonicalp

            Ath ();
            String Fdfsclientconfigfilepath = classPath + File.separator + client_config_file;

            Clientglobal.init (Fdfsclientconfigfilepath);
            Trackerclient = new Trackerclient ();

            Trackerserver = Trackerclient.getconnection ();

        Storageclient = new Storageclient (Trackerserver, storageserver);
        catch (Exception e) {e.printstacktrace (); }/** * <strong> method Overview: File Upload </strong> <br> * <strong> Date Created: 2016-9-26 10:26:11  </strong> <br> * @param fastdfsfile * file * @return Fileabsolutepath * @author Wang Liang */public static String upload (fastdfsfile file,namevaluepair[] valuepairs) {string[
        ] Uploadresults = null; try {uploadresults = StoragecLient.upload_file (File.getcontent (), File.getext (), valuepairs);
        catch (Exception e) {e.printstacktrace ();
        } String groupname = Uploadresults[0];

        String remotefilename = uploadresults[1]; String Fileabsolutepath = PROTOCOL + tracker_ngnix_addr//+ trackerserver.getinetsocketadd
                Ress () gethostname ()//+ SEPARATOR + tracker_ngnix_port + SEPARATOR + groupname
        + SEPARATOR + remotefilename;
    return fileabsolutepath; }
}

As shown above, load the fdfs_client.conf configuration file and construct tracker server and storage server when class initialization, and file uploads are implemented by Storageclient.upload_file method. The returned Uploadresults string array is exactly the filename, fixed two elements, Uploadresults[0] is the group name, and Uploadresults[1 is the file name after the group name, Finally, we have done a partial stitching in the method so that filemanager.upload directly can return the completed file path, the following is the way we call the upload method in the controller:

 @RequestMapping (value = "/add", method = requestmethod.post) public String Add (@Validated User User, Bindingresult br,multipartfile attach, HttpServletRequest request) throws IOException, MyException {if (Br.haserrors ())
    {return "User/add"; //Get file suffix name String ext = attach.getoriginalfilename (). substring (Attach.getoriginalfilename (). LastIndexOf (".")
    +1);
    Fastdfsfile file = new Fastdfsfile (Attach.getbytes (), ext);
    namevaluepair[] meta_list = new Namevaluepair[4];
    Meta_list[0] = new Namevaluepair ("FileName", Attach.getoriginalfilename ());
    META_LIST[1] = new Namevaluepair ("Filelength", String.valueof (Attach.getsize ()));
    META_LIST[2] = new Namevaluepair ("Fileext", ext);
    META_LIST[3] = new Namevaluepair ("Fileauthor", "Wangliang");
    String FilePath = Filemanager.upload (file,meta_list);
    User.setfilepath (FilePath);
    Users.put (User.getusername (), user);
return "Redirect:/user/users"; }

As shown above, the suffix name of the uploaded file is first intercepted by the string, then the Fastdfsfile object is constructed by the file suffix and the byte[of the file, then the meta_list namevaluepair[] array is constructed, which is mainly about the optional descriptive information of the file, Finally through the filemanager.upload can upload and return the absolute access path to the file, can be stored in db or files as required, and so on, no exception to the description of the file upload success, then look at the file download. File Download

Fastdfs-client-java provides the file download API requires two parameters, respectively, Group_name (group name) and remote_filename (filename), the source code is as follows:

/**
* Download file from Storage server
* @param group_name the group name of storage server
*   @param Remo Te_filename filename on storage server
* @return file Content/buff, return NULL if fail/public
byte[] downl Oad_file (String group_name, String remote_filename) throws IOException, MyException
{
    final long File_offset = 0 ;
    Final long download_bytes = 0;

    Return This.download_file (Group_name, Remote_filename, File_offset, download_bytes);

So we just have to get group_name and remote_filename here, because we've saved the absolute path (User.setfilepath (FilePath)) of the picture before uploading the file. So here you just get the absolute path and split the string, and then look at the download method encapsulated in FileManager:

/** * Overview of <strong> methods: file Downloads </strong> <br> * <strong> Date Created: 2016-9-26 a.m. 10 :28:21</strong> <br> * * @param string * groupname * @param string * Remotefilenam E * @return returned value comment here * @author Wang Liang/public static responseentity<byte[]> download (Str
    ing groupname, String remotefilename,string specfilename) {byte[] content = null;
    Httpheaders headers = new Httpheaders ();
        try {content = Storageclient.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) {//TODO auto-generated catch block E.printstacktrace ();
Return to new responseentity<byte[]> (content, headers, httpstatus.created); }

As shown above, 17 lines call the download method provided by Fastdfs-client-java, the download is successful after the return of a byte[], just combined with SPRINGMVC the official recommendation of the construction of httpentity to achieve file download, This download method I have specified more than one parameter specfilename The purpose is to ensure that the downloaded file name that is seen to the client is defined by the program, not the long string of default strings on the Fastdfs server. 18 line Specifies that the UTF-8 encoding enables our custom filename to support Chinese, which is very important, otherwise we will not be able to download correctly the renamed file containing Chinese . Finally, take a look at the download method in controller:

@RequestMapping (value = "/{username}/download", method = requestmethod.get) public
responseentity<byte[]> Download (@PathVariable String username, Model model,httpservletresponse response) throws IOException, MyException {
    User u = users.get (username);
    String FilePath = U.getfilepath ();
    String substr = filepath.substring (Filepath.indexof ("group"));
    String Group = Substr.split ("/") [0];
    String remotefilename = substr.substring (Substr.indexof ("/") +1);
    String Specfilename = username + substr.substring (substr.indexof ("."));
    Return Filemanager.download (group, remotefilename,specfilename);

As we thought before, the absolute path of the intercepting file gets group_name and file_name, and the incoming specfilename we customize here as the username (username) + After intercepting the file suffix name , look at the effect:

As above, click "Download Attachment", you can download and rename files correctly, so SPRINGMVC combined with Fastdfs file upload download has been all over. Summary

A brief introduction of SPRINGMVC combined with Fastdfs Java client Fastdfs-client-java to implement the Web file upload download, but this National day holiday is not a physical discomfort with the game, programmers or more should pay attention to health, the end.

Related Article

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.