概述
FastDFS 是一个由 C 语言实现的开源轻量级分布式文件系统,
支持 Linux、FreeBSD、AID 等 Unix 系统
解决了大数据存储和读写负载均衡等问题
适合存储 4KB~500MB
之间的小文件,如图片网站、短视频网站、文档、app 下载站等
FastDFS上传的流程
只要 storage 返回图片的路径图片名称,就能通过浏览器来访问图片
图片服务器在linux; nginx 做反向代理{图片服务器}
利用Java客户端调用FastDFS
tracker.config FastDFS的配置文件
文件上传服务器
使用
安装fastDFS服务器 配置
写配置文件 定义上传的地址
Java实现文件上传操作
配置tracker.config 文件上传地址
配置fileServerUrl 文件访问地址
实现
加载配置文件 tracker.conf 文件
初始化文件
创建TrackerClient
创建TrackerServer
创建StorgeServer
上传文件
代码实现
package com.doyens.gmall.product.controller;
import com.doyens.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* @author zrh
* @date 2022/4/26
* @apiNote
*/
@RestController
@RequestMapping("admin/product/")
public class FileUploadController {
@Value("${fileServer.url}")
private String fileUrl;
@RequestMapping("fileUpload")
public Result<String> fileUpload(MultipartFile file) throws Exception {
String configFile = this.getClass().getResource("/tracker.conf").getFile();
String path = null;
if (configFile != null) {
// 初始化
ClientGlobal.init(configFile);
// 创建trackerClient
TrackerClient trackerClient = new TrackerClient();
// 获取trackerService
TrackerServer trackerServer = trackerClient.getConnection();
// 创建storageClient1
StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
path = storageClient1.upload_appender_file1(file.getBytes(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
System.out.println(fileUrl + path);
}
return Result.ok(fileUrl + path);
}
}