12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package com.caimei.config;
- import com.github.tobato.fastdfs.domain.StorePath;
- import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
- import com.github.tobato.fastdfs.service.FastFileStorageClient;
- import lombok.RequiredArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.io.FileUtils;
- import org.apache.commons.io.FilenameUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import java.io.*;
- /**
- * @author Aslee
- * @date 2021/5/14
- */
- @Component
- @Slf4j
- public class FastDfsClient {
- @Autowired
- private FastFileStorageClient storageClient;
- // 文件上传
- public String uploadFile(String path) throws IOException {
- File file = new File(path);
- InputStream input = new FileInputStream(file);
- long size = FileUtils.sizeOf(file);
- String name = file.getName();
- String fileName = name.substring(name.lastIndexOf("/") + 1);
- StorePath storePath = storageClient.uploadFile(input, size, FilenameUtils.getExtension(fileName), null);
- input.close();
- return storePath.getFullPath();
- }
- // 文件下载
- public boolean downloadFile(String path, String downloadFilePath) throws IOException {
- File file = new File(downloadFilePath);
- FileOutputStream outputStream = null;
- // fastdfs 文件读取
- String filepath = path.substring(path.lastIndexOf("group1/") + 7);
- DownloadByteArray callback = new DownloadByteArray();
- byte[] content = storageClient.downloadFile("group1", filepath, callback);
- // 数据写入指定文件夹中
- outputStream = new FileOutputStream(file);
- outputStream.write(content);
- outputStream.close();
- return true;
- }
- public void deleteFile(String storagePath) {
- try {
- String filepath = storagePath.substring(storagePath.lastIndexOf("group1/") + 7);
- storageClient.deleteFile("group1", filepath);
- } catch (Exception e) {
- log.error("删除失败!-------------》" + e);
- }
- }
- }
|