fastDFS與java整合檔案上傳下載

來源:互聯網
上載者:User

標籤:apach   ofo   auth   業務   XML   檔案複製   spl   ati   oba   

準備
  1. 下載fastdfs-client-java源碼

源碼地址 密碼:s3sw

  1. 修改pom.xml
    第一個plugins是必需要的,是maven用來編譯的外掛程式,第二個是maven打源碼包的,可以不要。

    <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. fastdfs-client-java 打包
    直接項目右鍵,run as maven install
    install成功後,fastdfs-client-java就成功的被安裝到本地倉庫了。
    ---

    編寫工具類:
  • fdfs_client.conf檔案複製一份放到自己項目的resource下面;修改裡面的tracker.server,其它的都不用動:
  • 在項目的pom.xml中添加依賴

    <dependency><groupId>org.csource</groupId><artifactId>fastdfs-client-java</artifactId><version>1.27-SNAPSHOT</version></dependency>
  • 首先來實現檔案上傳,fastdfs-client-java的上傳是通過傳入一個byte[ ]來完成的,簡單看一下源碼:

    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);}
檔案屬性
package com.wuwii.utils;import java.io.Serializable;import java.util.Arrays;/** * @ClassName FastDFSFile * @Description FastDFS上傳檔案業務對象 * @author zhangkai * @date 2017年7月18日 */public class FastDFSFile implements Serializable{    private static final long serialVersionUID = 2637755431406080379L;    /**     * 檔案二進位     */    private byte[] content;    /**     * 檔案名稱     */    private String name;    /**     * 檔案長度     */    private Long size;        public FastDFSFile(){            }    public FastDFSFile(byte[] content, String name, Long size){        this.content = content;        this.name = name;        this.size = size;    }        public 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 Long getSize() {        return size;    }    public void setSize(Long size) {        this.size = size;    }    public static long getSerialversionuid() {        return serialVersionUID;    }}
編寫FastDFS工具類
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工具類 * @author zhangkai * @date 2017年7月18日 */public class FastDFSUtils implements Serializable{    /**     *      */    private static final long serialVersionUID = -4462272673174266738L;    private static TrackerClient trackerClient;    private static TrackerServer trackerServer;    private static StorageClient1 storageClient1;        static {        try {            //clientGloble讀設定檔            ClassPathResource resource = new ClassPathResource("fdfs_client.conf");            ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());            //trackerclient            trackerClient = new TrackerClient();            trackerServer = trackerClient.getConnection();            //storageclient            storageClient1 = new StorageClient1(trackerServer,null);         } catch (Exception e) {            e.printStackTrace();        }    }        /**     * fastDFS檔案上傳     * @param file 上傳的檔案 FastDFSFile     * @return String 返迴文件的絕對路徑     */    public static String uploadFile(FastDFSFile file){        String path = null;        try {            //副檔名            String ext = FilenameUtils.getExtension(file.getName());            //mata list是表檔案的描述            NameValuePair[] mata_list = new NameValuePair[3];            mata_list[0] = new NameValuePair("fileName",file.getName());            mata_list[1] = new NameValuePair("fileExt",ext);            mata_list[2] = new NameValuePair("fileSize",String.valueOf(file.getSize()));            path = storageClient1.upload_file1(file.getContent(), ext, mata_list);        } catch (Exception e) {            e.printStackTrace();        }         return path;    }        /**     * fastDFS檔案下載     * @param groupName 組名     * @param remoteFileName 檔案名稱     * @param specFileName 真實檔案名稱     * @return ResponseEntity<byte[]>     */    @org.jetbrains.annotations.NotNull    public static ResponseEntity<byte[]> downloadFile(String groupName, String remoteFileName, String specFileName){        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);    }        /**     * 根據fastDFS返回的path得到檔案的組名     * @param path fastDFS返回的path     * @return     */    public static String getGroupFormFilePath(String path){        return path.split("/")[0];    }        /**     * 根據fastDFS返回的path得到檔案名稱     * @param path fastDFS返回的path     * @return     */    @NotNull    public static String getFileNameFormFilePath(String path) {        return path.substring(path.indexOf("/")+1);    }}
測試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控制器 * @author zhangkai * */@Controller@RequestMapping(value = "/fastdfs")public class FastFDSController {     @RequestMapping(value = "/upload", method = RequestMethod.POST)    public String upload (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 block            e.printStackTrace();        }        return null;    }          @RequestMapping(value = "/download")     public ResponseEntity<byte[]> download (String path, String specFileName){         String filename = FastDFSUtils.getFileNameFormFilePath(path);         String group = FastDFSUtils.getGroupFormFilePath(path);         return FastDFSUtils.downloadFile(group, filename, specFileName);     }}
最後附上讀取設定檔的工具類PropertyUtil
package com.wuwii.utils;import java.io.InputStream;import java.util.Properties;/** * @ClassName PropertyUtil * @Description 讀取設定檔的內容(key,value) * @author zhangkai * @date 2017年7月18日 */public class PropertyUtil {    public static final Properties PROP = new Properties();    /**      * @Method: get      * @Description: 讀取設定檔的內容(key,value)     * @param key     * @return String     * @throws      */    public static String get(String key) {        if (PROP.isEmpty()) {            try {                InputStream in = PropertyUtil.class.getResourceAsStream("/config.properties");                PROP.load(in);                in.close();            } catch (Exception e) {}        }        return PROP.getProperty(key);    }}
測試上傳!

下載

下載就很簡單了,因為直接獲得到二進位流了,返回給用戶端即可。
下載需要主要的是,要注意從FastDFS返回的檔案名稱是這種隨機碼,因此我們需要在上傳的時候將檔案本身的名字存到資料庫,再到下載的時候對檔案頭重新設定名字即可。

fastDFS與java整合檔案上傳下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.