天天看點

引用fastdfs圖檔伺服器

1. 引入jar包

<dependency>
            <groupId>net.arccode</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0</version>
   </dependency>
           

2 fast伺服器調用

package com.ehulian.dev.compoents.upload.fastdfs.service;

import com.ehulian.dev.compoents.upload.fastdfs.dto.FastDFSDto;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.BufferedOutputStream;
import java.io.IOException;
@Slf4j
public class FastDFSClient {

        private TrackerClient trackerClient = null;
        private TrackerServer trackerServer = null;
        private StorageServer storageServer = null;
        private StorageClient1 storageClient = null;


        public FastDFSClient(String serviceUrl) throws Exception {
            ClientGlobal.initByTrackers(serviceUrl);
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageServer = null;
        }

    /**
     * 上傳檔案方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @return
     * @throws Exception
     */
    public String uploadFile(FastDFSDto fastDFSDto) {
        String result=null;
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            result = storageClient.upload_file1(fastDFSDto.getUrl(), fastDFSDto.getExtName(), null);
        } catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return result;
    }


    /**
     * 上傳檔案方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @return
     * @throws Exception
     */
    public String uploadFile(byte [] fileContent, String extName, NameValuePair[] metas) {
        String result=null;
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            result = storageClient.upload_file1(fileContent,extName,metas);
        }catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return result;
    }

    /**
     * 檔案下載下傳到磁盤
     * @param path 圖檔路徑
     * @param output 輸出流 中包含要輸出到磁盤的路徑
     * @return -1失敗,0成功
     */
    public int download_file(String path,BufferedOutputStream output) {
        int result=-1;
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            byte[] b = storageClient.download_file1(path);
            try{
                if(b != null){
                    output.write(b);
                    result=0;
                }
            }catch (Exception e){} //使用者可能取消了下載下傳
            finally {
                if (output != null){
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return result;
    }
    /**
     * 擷取檔案數組
     * @param path 檔案的路徑 如group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public byte[] download_bytes(String path) {
        byte[] b=null;
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            b = storageClient.download_file1(path);
        } catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return b;
    }

    /**
     * 删除檔案
     * @param group 組名 如:group1
     * @param storagePath 不帶組名的路徑名稱 如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return -1失敗,0成功
     */
    public Integer delete_file(String group ,String storagePath){
        int result=-1;
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            result = storageClient.delete_file(group, storagePath);
        } catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return  result;
    }
    /**
     *
     * @param storagePath  檔案的全部路徑 如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return -1失敗,0成功
     * @throws IOException
     * @throws Exception
     */
    public Integer delete_file(String storagePath){
        int result=-1;
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            result = storageClient.delete_file1(storagePath);
        } catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return  result;
    }

    /**
     * 擷取遠端伺服器檔案資源資訊
     * @param groupName   檔案組名 如:group1
     * @param remoteFileName M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
     * @return
     */
    public FileInfo getFile(String groupName, String remoteFileName){
        try {
            storageClient = new StorageClient1(trackerServer, storageServer);
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            log.error("出現異常原因:{}",e);
        }
        return null;
    }
}
           

注意  

我用到的是   ClientGlobal.initByTrackers(serviceUrl);  生成

是以我隻需要提供serviceUrl   

controller

package com.ehulian.dev.compoents.upload.fastdfs.controller;

import com.ehulian.dev.common.base.utils.StringUtil;
import com.ehulian.dev.common.model.pojo.ServerResponse;
import com.ehulian.dev.compoents.upload.fastdfs.dto.ExeDfsDto;
import com.ehulian.dev.compoents.upload.fastdfs.dto.FastDFSDto;
import com.ehulian.dev.compoents.upload.fastdfs.service.FastDFSClient;
import com.ehulian.dev.compoents.upload.fastdfs.util.Fastdfs;
import com.ehulian.dev.compoents.upload.fastdfs.util.ImageUtil;
//import it.sauronsoftware.jave.Encoder;
//import it.sauronsoftware.jave.EncoderException;
//import it.sauronsoftware.jave.MultimediaInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * fastdfs 資料調用
 *
 * @author ggwang
 * @date 2019/1/7 10:54
 */
@Slf4j
@RestController
@RequestMapping(value = "/fastdfs")
public class FastDfsController {

    @Autowired
    private Fastdfs fastdfs;

    @RequestMapping(value = "/formdata", method = RequestMethod.POST)
    public ResponseEntity fastDFSformdata(MultipartFile file) throws Exception {
        if (file == null) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("上傳檔案不能為空"));
        }
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        Map<String, String> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        String path = fastDFSClient.uploadFile(file.getBytes(), "jpg", null);
        if (StringUtils.isEmpty(path)) {
            fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
            path = fastDFSClient.uploadFile(file.getBytes(), "jpg", null);
            if (StringUtils.isEmpty(path)) {
                return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("錯誤的路徑"));
            }
        }
        sb.append(fastdfs.getBusinessUrl()).append(path);
        result.put("url", sb.toString());
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess(result));
    }

    @RequestMapping(value = "/dfsFile", method = RequestMethod.POST)
    public ResponseEntity fastDFSFile(ExeDfsDto exeDfsDto) throws Exception {
        if (exeDfsDto.getFile() == null) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("上傳檔案不能為空"));
        }
        if(!StringUtil.isNotBlanck(exeDfsDto.getExtName())){
            String sor=exeDfsDto.getFile().getOriginalFilename();
            sor=sor.substring(sor.lastIndexOf(".")+1,sor.length());
            exeDfsDto.setExtName(sor);
        }
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        Map<String, String> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        String path = fastDFSClient.uploadFile(exeDfsDto.getFile().getBytes(), exeDfsDto.getExtName(), null);
        if (StringUtils.isEmpty(path)) {
            fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
            path = fastDFSClient.uploadFile(exeDfsDto.getFile().getBytes(), exeDfsDto.getExtName(), null);
            if (StringUtils.isEmpty(path)) {
                return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("錯誤的路徑"));
            }
        }
        sb.append(fastdfs.getBusinessUrl()).append(path);
        result.put("url", sb.toString());
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess(result));
    }
//    //關于擷取音頻的時長的方法
//    public static void main(String[] args) throws EncoderException {
//        File source =new File("C:\\Users\\Administrator\\Desktop\\素材資料\\9919.wav ");
//        Encoder encoder = new Encoder();
//        MultimediaInfo m = encoder.getInfo(source);
//        long ls = m.getDuration();
//        long duration = ls/1000;
//        System.out.println("此視訊時長為:"+ls/60000+"分"+(ls/1000-ls/60000*60)+"秒!");
//    }
    /**
     * 本地路徑 -- 不壓縮檔案  c:/ .....
     *
     * @param fastDFSlsDto
     * @return
     */
    @RequestMapping(value = "/localpath", method = RequestMethod.POST)
    public ResponseEntity fastDFSlocalpath(@RequestBody FastDFSDto fastDFSlsDto) throws Exception {
        if (StringUtils.isEmpty(fastDFSlsDto.getUrl())) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("圖檔路徑不能為空"));
        }
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        Map<String, String> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        String path = fastDFSClient.uploadFile(fastDFSlsDto);
        if (StringUtils.isEmpty(path)) {
            fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
            path = fastDFSClient.uploadFile(fastDFSlsDto);
            if (StringUtils.isEmpty(path)) {
                return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("錯誤的路徑"));
            }
        }
        sb.append(fastdfs.getBusinessUrl()).append(path);
        result.put("url", sb.toString());
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess(result));
    }

    /**
     * 網上路徑 -- 不壓縮檔案  http:// .....  https://....
     *
     * @param fastDFSDto
     * @return
     */
    @RequestMapping(value = "/onlinepath", method = RequestMethod.POST)
    public ResponseEntity fastDFSImgOnline(@RequestBody FastDFSDto fastDFSDto) throws Exception {
        if (StringUtils.isEmpty(fastDFSDto.getUrl())) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("圖檔路徑不能為空"));
        }
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        Map<String, String> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        sb.append(fastdfs.getBusinessUrl());
        File file = new File(fastDFSDto.getUrl());
        byte[] bytes = ImageUtil.getImageFromNetByUrl(fastDFSDto.getUrl());
        InputStream inputStream = new ByteArrayInputStream(bytes);
        MultipartFile multipartFile = null;
        try {
            multipartFile = new MockMultipartFile(file.getName(), inputStream);
            String path = fastDFSClient.uploadFile(multipartFile.getBytes(), fastDFSDto.getExtName(), null);
            if (StringUtils.isEmpty(path)) {
                fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
                path = fastDFSClient.uploadFile(multipartFile.getBytes(), fastDFSDto.getExtName(), null);
                if (StringUtils.isEmpty(path)) {
                    return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("錯誤的路徑"));
                }
            }
            sb.append(path);
            result.put("url", sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok().body(ServerResponse.buildByErrorMessage("圖檔服務無法使用"));
        }
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess(result));
    }

    /**
     * 網上路徑 -- 不壓縮檔案  http:// .....  https://....
     *
     * @param fastDFSDto
     * @return
     */
    @RequestMapping(value = "/onByteImg", method = RequestMethod.POST)
    public ResponseEntity onByteImg(@RequestBody FastDFSDto fastDFSDto) throws Exception {
        Map<String, String> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        sb.append(fastdfs.getBusinessUrl());
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        try {
            String path = fastDFSClient.uploadFile(fastDFSDto.getBytes(), fastDFSDto.getExtName(), null);
            if (StringUtils.isEmpty(path)) {
                fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
                path = fastDFSClient.uploadFile(fastDFSDto.getBytes(), fastDFSDto.getExtName(), null);
                if (StringUtils.isEmpty(path)) {
                    return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("錯誤的路徑"));
                }
            }
            sb.append(path);
            result.put("url", sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok().body(ServerResponse.buildByErrorMessage("圖檔服務無法使用"));
        }
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess(result));
    }

    /**
     * 下載下傳圖檔
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.POST)
    public ResponseEntity downloadFile(@RequestBody FastDFSDto fastDFSDto) throws Exception {
        if (StringUtils.isEmpty(fastDFSDto.getUrl()) || StringUtils.isEmpty(fastDFSDto.getAddress())) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("參數異常"));
        }
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fastDFSDto.getAddress()));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("解析失敗"));
        }
        Integer sign = fastDFSClient.download_file(fastDFSDto.getUrl(), bufferedOutputStream);
        if (sign.intValue() != 0) {
            fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
            sign = fastDFSClient.download_file(fastDFSDto.getUrl(), bufferedOutputStream);
            if (sign.intValue() != 0) {
                return ResponseEntity.ok().body(ServerResponse.buildByError());
            }
        }
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess());
    }

    /**
     * 圖檔傳回位元組
     * 傳回byte []
     */
    @RequestMapping(value = "/downloadBytes", method = RequestMethod.POST)
    public ResponseEntity<?> downloadBytes(@RequestBody FastDFSDto fastDFSDto) throws Exception {
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        if (StringUtils.isEmpty(fastDFSDto.getUrl())) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("參數異常"));
        }
        String url = fastDFSDto.getUrl().replace(fastdfs.getBusinessUrl(), "");
        byte[] sign = fastDFSClient.download_bytes(url);
        if (sign == null) {
            sign = fastDFSClient.download_bytes(url);
            if (sign == null) {
                return ResponseEntity.ok().body(ServerResponse.buildByErrorMessage("該圖檔無法解析"));
            }
        }
        return ResponseEntity.ok(sign);
    }

    /**
     * 删除圖檔
     * 傳回byte []
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    public ResponseEntity deleteFile(@RequestBody FastDFSDto fastDFSDto) throws Exception {
        FastDFSClient  fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());
        if (StringUtils.isEmpty(fastDFSDto.getUrl())) {
            return ResponseEntity.badRequest().body(ServerResponse.buildByErrorMessage("參數異常"));
        }
        String url = fastDFSDto.getUrl().replace(fastdfs.getBusinessUrl(), "");
        Integer sign = fastDFSClient.delete_file(url);
        if (sign.intValue() != 0) {
            sign = fastDFSClient.delete_file(url);
            if (sign.intValue() != 0) {
                return ResponseEntity.ok().body(ServerResponse.buildByError());
            }
        }
        return ResponseEntity.ok().body(ServerResponse.buildBySuccess());

    }

}
           

常見錯誤分析

fastdfs上傳報錯 recv package size -1 != 10  

這錯誤一般是上傳出錯 但是第二次上傳又是正常的  一般在反複調用時候出現    

文中一個類出現兩次  就是為了屏蔽該類錯誤

fastDFSClient = new FastDFSClient(fastdfs.getServiceUrl());      

java.net.SocktetException:  Broken pipe(write failed)  

     這是因為圖檔伺服器連接配接不上  建議檢查fastdfs與fastdfs伺服器之間連接配接通道

繼續閱讀