java操作fastdfs包括文件上传、下载、删除

pom.xml

 <!-- FastDFS -->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.5</version>
        </dependency>

application.yml

# 分布式文件系统FDFS配置
fdfs:
  #读取时间
  so-timeout: 30000
  #连接超时时间
  connect-timeout: 60000
  # TrackerList路径,支持多个121.41.118.73
  tracker-list:
    - ip:22122
  # 自定义配置,文件访问路径(这个ip为nginx的ip)http://121.41.118.73:8888
  fileUrl: http://ip:8888

上传

 @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Value("${fdfs.fileUrl}")
    private String fileUrl; // Nginx访问FastDFS中文件的路径

    /**
     * fastdfs上传文件
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/fastdfs/upload")
    public BaseResult<String> fastdfsUpload(MultipartFile file) throws IOException {
        // MultipartFile对象不能再服务间传递,必须转为byte数组
        byte[] fileBytes = file.getBytes();
        String fileName = file.getOriginalFilename();
        String imageUrl = "";
        if (fileBytes.length != 0) {
            try {
                // 1.将文件字节数组转为输入流
                InputStream inputStream = new ByteArrayInputStream(fileBytes);
                // 2.获取文件的后缀名
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 3.上传文件
                StorePath storePath = fastFileStorageClient.uploadFile(inputStream, inputStream.available(), fileSuffix, null);
                // 4.返回图片路径
                imageUrl = fileUrl + "/" + storePath.getFullPath();

            } catch (IOException ioException) {
                return new BaseResult<>(CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getCode(), CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getMessage(), null);
            }
        } else {
            return new BaseResult<>(CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getCode(), CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getMessage(), null);
        }
        return BaseResult.ok(imageUrl);
    }

删除

/**
     * fastdfs删除文件
     *
     * @param filePath 文件路径
     * @return
     */
    @PostMapping("/fastdfs/deleteUrl")
    public BaseResult fastdfsDelete(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
        return BaseResult.ok();
    }

下载

 /**
     * fastdfs下载文件
     *
     * @param filePath 文件路径
     * @return
     */
    @GetMapping("/fastdfs/download")
    public void fastdfsDownLoad(String filePath) throws IOException {
        //http://ip:8888/group1/M00/00/00/rBoX5mR0ulSAIukOAASzmDL13HM352.jpg
        byte[] bytes = null;
        try {
            //返回"/"第三次出现的位置
            int index1 = StringUtils.ordinalIndexOf(filePath,"/",3);
            int index2 = StringUtils.ordinalIndexOf(filePath,"/",4);
            String group = filePath.substring(index1+1,index2);
            String filepath = filePath.substring(filePath.lastIndexOf(group + "/")+7);
            DownloadByteArray callback = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, filepath,callback);

            //文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\A多媒体\\图库\\fastdfs");
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();

        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }

全部代码

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import jkw.result.BaseResult;
import jkw.result.CodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Value("${fdfs.fileUrl}")
    private String fileUrl; // Nginx访问FastDFS中文件的路径

    /**
     * fastdfs上传文件
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/fastdfs/upload")
    public BaseResult<String> fastdfsUpload(MultipartFile file) throws IOException {
        // MultipartFile对象不能再服务间传递,必须转为byte数组
        byte[] fileBytes = file.getBytes();
        String fileName = file.getOriginalFilename();
        String imageUrl = "";
        if (fileBytes.length != 0) {
            try {
                // 1.将文件字节数组转为输入流
                InputStream inputStream = new ByteArrayInputStream(fileBytes);
                // 2.获取文件的后缀名
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                // 3.上传文件
                StorePath storePath = fastFileStorageClient.uploadFile(inputStream, inputStream.available(), fileSuffix, null);
                // 4.返回图片路径
                imageUrl = fileUrl + "/" + storePath.getFullPath();

            } catch (IOException ioException) {
                return new BaseResult<>(CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getCode(), CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getMessage(), null);
            }
        } else {
            return new BaseResult<>(CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getCode(), CodeEnum.FILE_FASTDFS_UPLOAD_ERROR.getMessage(), null);
        }
        return BaseResult.ok(imageUrl);
    }

    /**
     * fastdfs删除文件
     *
     * @param filePath 文件路径
     * @return
     */
    @PostMapping("/fastdfs/deleteUrl")
    public BaseResult fastdfsDelete(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
        return BaseResult.ok();
    }

    /**
     * fastdfs下载文件
     *
     * @param filePath 文件路径
     * @return
     */
    @GetMapping("/fastdfs/download")
    public void fastdfsDownLoad(String filePath) throws IOException {
        //http://ip:8888/group1/M00/00/00/rBoX5mR0ulSAIukOAASzmDL13HM352.jpg
        byte[] bytes = null;
        try {
            //返回"/"第三次出现的位置
            int index1 = StringUtils.ordinalIndexOf(filePath,"/",3);
            int index2 = StringUtils.ordinalIndexOf(filePath,"/",4);
            String group = filePath.substring(index1+1,index2);
            String filepath = filePath.substring(filePath.lastIndexOf(group + "/")+7);
            DownloadByteArray callback = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, filepath,callback);

            //文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream("D:\\A多媒体\\图库\\fastdfs");
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();

        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }

}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月木@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值