在Spring Boot中实现分布式文件存储:FastDFS的应用
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
@RestController
public class FileController {
@Autowired
private FastFileStorageClient fastFileStorageClient;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
"jpg", null);
return storePath.getFullPath();
}
@GetMapping("/download")
public void downloadFile(@RequestParam("fileUrl") String fileUrl, @RequestParam("response") HttpServletResponse response) {
try {
StorePath storePath = StorePath.parseFromUrl(fileUrl);
byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
response.getOutputStream().write(bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个代码实例提供了文件上传和下载的简单操作。上传操作接收一个MultipartFile
对象,并使用FastFileStorageClient
上传到FastDFS。下载操作接收一个文件路径,并使用FastFileStorageClient
下载文件。这里假设DownloadByteArray
是一个实现了DownloadCallback<byte[]>
的类,用于处理下载的字节数据。
评论已关闭