FastDfsClient.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 lombok.extern.slf4j.Slf4j;
  7. import org.apache.commons.io.FileUtils;
  8. import org.apache.commons.io.FilenameUtils;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Component;
  11. import java.io.*;
  12. /**
  13. * @author Aslee
  14. * @date 2021/5/14
  15. */
  16. @Component
  17. @Slf4j
  18. public class FastDfsClient {
  19. @Autowired
  20. private FastFileStorageClient storageClient;
  21. // 文件上传
  22. public String uploadFile(String path) throws IOException {
  23. File file = new File(path);
  24. InputStream input = new FileInputStream(file);
  25. long size = FileUtils.sizeOf(file);
  26. String name = file.getName();
  27. String fileName = name.substring(name.lastIndexOf("/") + 1);
  28. StorePath storePath = storageClient.uploadFile(input, size, FilenameUtils.getExtension(fileName), null);
  29. input.close();
  30. return storePath.getFullPath();
  31. }
  32. // 文件下载
  33. public boolean downloadFile(String path, String downloadFilePath) throws IOException {
  34. File file = new File(downloadFilePath);
  35. FileOutputStream outputStream = null;
  36. // fastdfs 文件读取
  37. String filepath = path.substring(path.lastIndexOf("group1/") + 7);
  38. DownloadByteArray callback = new DownloadByteArray();
  39. byte[] content = storageClient.downloadFile("group1", filepath, callback);
  40. // 数据写入指定文件夹中
  41. outputStream = new FileOutputStream(file);
  42. outputStream.write(content);
  43. outputStream.close();
  44. return true;
  45. }
  46. public void deleteFile(String storagePath) {
  47. try {
  48. String filepath = storagePath.substring(storagePath.lastIndexOf("group1/") + 7);
  49. storageClient.deleteFile("group1", filepath);
  50. } catch (Exception e) {
  51. log.error("删除失败!-------------》" + e);
  52. }
  53. }
  54. }