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 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 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; } }