fastdfs-client-java工具類封裝

來源:互聯網
上載者:User

標籤:tip   val   const   image   字元   win   oca   fas   get   

FastDFS是通過StorageClient來執行上傳操作的

通過看源碼我們知道,FastDFS有兩個StorageClient工具類。

StorageClient的上傳方法upload_file(...)返回的是字串數組String[],

如[group1,M00/00/00/wKgAb1dBK2iANrayAA1rIuRd3Es112.jpg]

StorageClient1的上傳方法upload_file(...)返回的是字串數組String,

如group1/M00/00/00/wKgAb1dBK2iANrayAA1rIuRd3Es112.jpg,也就是已經幫我們拼接好了

所以使用StorageClient1的上傳方法更方便,不用我們自己拼接了。

FastDFSClient

 

public class FastDFSClient {
    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    //使用StorageClient1進行上傳
    private StorageClient1 storageClient1 = null;

    public FastDFSClient(String conf) throws Exception {
        //擷取classpath路徑下設定檔"fdfs_client.conf"的路徑
        //conf直接寫相對於classpath的位置,不需要寫classpath:
        String configPath = this.getClass().getClassLoader().getResource(conf).getFile();
        System.out.println(configPath);
        ClientGlobal.init(configPath);

        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = trackerClient.getStoreStorage(trackerServer);
        storageClient1 = new StorageClient1(trackerServer, storageServer);
    }

    public String uploadFile(byte[] file_buff, String file_ext_name) throws Exception {

        String result = storageClient1.upload_file1(file_buff, file_ext_name, null);

        return result;
    }

    public String uploadFile(String local_filename, String file_ext_name) throws Exception {

        String result = storageClient1.upload_file1(local_filename, file_ext_name, null);

        return result;
    }
}

測試

 
public class FastDFSTest {    public static void main(String[] args) throws Exception {        //不要帶classpath        FastDFSClient client = new FastDFSClient("properties/fdfs_client.conf");        String result = client.uploadFile("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg", "jpg");        System.out.println(result);    }}


                                                                                        

在項目中,圖片上傳的實現

Service層

@Servicepublic class PictureServiceImpl implements PictureService {    //將需要拼接的ip地址寫在設定檔中,交給spring管理    @Value("${IAMGE_SERVER_BASE_UEL}")    private String IAMGE_SERVER_BASE_UEL;    @Override    public PictureResult uploadPic(MultipartFile picFile) {        PictureResult result = new PictureResult();        //判斷圖片是否為空白        if (picFile.isEmpty()) {            result.setError(1);            result.setMessage("圖片為空白");            return result;        }        //上傳到圖片伺服器        try {            //擷取圖片副檔名            String originalFilename = picFile.getOriginalFilename();            //取副檔名,不要"."            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);            FastDFSClient client = new FastDFSClient("properties/fdfs_client.conf");            String url = client.uploadFile(picFile.getBytes(), extName);            //拼接圖片伺服器的ip的地址(寫設定檔中)            url = IAMGE_SERVER_BASE_UEL + url;            //把url響應給用戶端            result.setError(0);            result.setUrl(url);        } catch (Exception e) {            e.printStackTrace();            result.setError(1);            result.setMessage("圖片上傳失敗");        }        return result;    }}

表現層

@Controllerpublic class PictureController {    @Autowired    PictureService pictureService;    @RequestMapping("/pic/upload")    @ResponseBody    public PictureResult uploadFile(MultipartFile uploadFile){        PictureResult result = pictureService.uploadPic(uploadFile);        return result;    }}

經測試發現,chrome可以正常上傳,但是firefox不能,說明相容性有問題

這就要求我們將返回的資料轉換成一個字串文本,瀏覽器對字串的相容性最好、

封裝一個工具類

JsonUtils
import java.util.List;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.JavaType;import com.fasterxml.jackson.databind.ObjectMapper;public class JsonUtils {    // 定義jackson對象    private static final ObjectMapper MAPPER = new ObjectMapper();    /**     * 將對象轉換成json字串。     */    public static String objectToJson(Object data) {        try {            String string = MAPPER.writeValueAsString(data);            return string;        } catch (JsonProcessingException e) {            e.printStackTrace();        }        return null;    }    /**     * 將json結果集轉化為對象     */    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {        try {            T t = MAPPER.readValue(jsonData, beanType);            return t;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    /**     * 將json資料轉換成pojo對象list     */    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);        try {            List<T> list = MAPPER.readValue(jsonData, javaType);            return list;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}

修改後的controller

@Controllerpublic class PictureController {    @Autowired    PictureService pictureService;    @RequestMapping("/pic/upload")    @ResponseBody    public String uploadFile(MultipartFile uploadFile){        PictureResult result = pictureService.uploadPic(uploadFile);        //需要把java對象轉換成json資料        String json = JsonUtils.objectToJson(result);        return json;    }}

  

fastdfs-client-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.