FastDFS文件上傳實現

文件信息封裝

文件上傳一般都有文件的名字、文件的內容、文件的擴展名、文件的md5值、文件的作者等相關屬性,我們可以創建一個對象封裝這些屬性,代碼如下:

public class FastDFSFile {
    //文件名字
    private String name;
    //文件內容
    private byte[] content;
    //文件擴展名
    private String ext;
    //文件MD5摘要值
    private String md5;
    //文件創建作者
    private String author;

    public FastDFSFile(String name, byte[] content, String ext, String height,
                       String width, String author) {
        super();
        this.name = name;
        this.content = content;
        this.ext = ext;
        this.author = author;
    }

    public FastDFSFile(String name, byte[] content, String ext) {
        super();
        this.name = name;
        this.content = content;
        this.ext = ext;
    }

    // getter and setter ...
}

文件上傳的工具類

package com.changgou.file.util;
import com.changgou.file.pojo.FastDFSFile;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
 * @author :gzy
 * @date :Created in 2019/8/13
 * @description :
 * @version: 1.0
 */

public class FastDFSClient {
    private static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    private static TrackerClient trackerClient = null;

    private static StorageClient1 storageClient1 = null;

    private static TrackerServer trackerServer = null;

    private static StorageServer storageServer = null;

    //靜態代碼塊   爲了上傳文件  初始化加載文件的上傳配置文件  (文件中包含  上傳文件的地址 連接時間 讀取時間 編碼集 等
    static {
        try {
            //spring提供的類用來處理classpath下的資源,fdfs_client.conf就在classath下。這裏獲取絕對路徑
            String absolutePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            //jar包中的全局類,底層利用流加載配置信息,流要求路徑爲絕對路徑
            ClientGlobal.init(absolutePath);
             //創建跟蹤器對象
            trackerClient = new TrackerClient();
            //連接(保存讓你連接存儲節點的地址)
            trackerServer = trackerClient.getConnection();
            //創建storage客戶端,第二個參數個人感覺沒什麼用所以傳個空值意思下
            storageClient1 = new StorageClient1(trackerServer, storageServer);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ClientGlobal is fail:{}",e.getMessage());
        }

    }

    /**
     * 上傳文件
     *
     * @param file
     * @return 文件的路徑
     */
    public static String uploadFile(FastDFSFile file){
        System.out.println("上傳文件");
        NameValuePair[] nameValuePairs = new NameValuePair[1];
        nameValuePairs[0] = new NameValuePair(file.getAuthor());
        try {
            return storageClient1.upload_file1(file.getContent(),file.getExt(),nameValuePairs);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("upload file is fail: {} ",e.getMessage());
        }
        return null;

    }

    /**
     * 下載文件
     * @param path
     * @return  文件對象
     */
    public static InputStream downFile(String path){

        try {
            byte[] bytes = storageClient1.download_file1(path);
            return new ByteArrayInputStream(bytes);
        } catch (Exception e){
            e.getStackTrace();
            logger.error("download file is fail : {}" ,e.getMessage());
        }


        return null;
    }


    /**
     *  刪除文件
     * @param path
     *
     */
    public static void deleteFile(String path){

        try {
            storageClient1.delete_file1(path);
        } catch (Exception e)  {
            e.printStackTrace();
            logger.error("delete file is fail : {}",e.getMessage());
        }
    }
    /***
     * 獲取Tracker服務地址
     * @return
     * @throws IOException
     */
    public static String getTrackerUrl() throws IOException {
        return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
    }
}

文件上傳

創建一個FileController,在該控制器中實現文件上傳操作,代碼如下:

package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSFile;
import com.changgou.file.util.FastDFSClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * @author :gzy
 * @date :Created in 2019/8/13
 * @description :
 * @version: 1.0
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
//打印日誌
    private Logger logger=LoggerFactory.getLogger(FileController.class);
    @RequestMapping("/updown")
    public Result updownfile(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
//阿帕奇的根據文件名稱獲取文件後綴名
        String extension = FilenameUtils.getExtension(originalFilename);
        try {
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,file.getBytes(),extension);
            String path = FastDFSClient.uploadFile(fastDFSFile);
            System.out.println(FastDFSClient.getTrackerUrl()+path);
            return new Result(true,StatusCode.OK,"上傳成功",path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章