FastDfsClient.java 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package com.caimei.config;
  2. import com.github.tobato.fastdfs.domain.StorePath;
  3. import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
  4. import com.github.tobato.fastdfs.service.FastFileStorageClient;
  5. import lombok.RequiredArgsConstructor;
  6. import org.apache.commons.io.FileUtils;
  7. import org.apache.commons.io.FilenameUtils;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Component;
  10. import java.io.*;
  11. /**
  12. * @author Aslee
  13. * @date 2021/5/14
  14. */
  15. @Component
  16. public class FastDfsClient {
  17. @Autowired
  18. private FastFileStorageClient storageClient;
  19. // 文件上传
  20. public String uploadFile(String path) throws IOException {
  21. File file = new File(path);
  22. InputStream input = new FileInputStream(file);
  23. long size = FileUtils.sizeOf(file);
  24. String name = file.getName();
  25. String fileName = name.substring(name.lastIndexOf("/") + 1);
  26. StorePath storePath = storageClient.uploadFile(input, size, FilenameUtils.getExtension(fileName), null);
  27. input.close();
  28. return storePath.getFullPath();
  29. }
  30. // 文件下载
  31. public boolean downloadFile(String path, String downloadFilePath) throws IOException {
  32. File file = new File(downloadFilePath);
  33. FileOutputStream outputStream = null;
  34. // fastdfs 文件读取
  35. String filepath = path.substring(path.lastIndexOf("group1/") + 7);
  36. DownloadByteArray callback = new DownloadByteArray();
  37. byte[] content = storageClient.downloadFile("group1", filepath, callback);
  38. // 数据写入指定文件夹中
  39. outputStream = new FileOutputStream(file);
  40. outputStream.write(content);
  41. outputStream.close();
  42. return true;
  43. }
  44. }