天天看点

引用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服务器之间连接通道

继续阅读