FastDfsClient.java 1.6 KB

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