1.引入依赖
配置文件fdfs_client.conf
connect_timeout = 30
network_timeout = 30
charset = utf-8
http.tracker_http_port = 7777
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
tracker_server = ip:22122
2.maven好像无法自动引入jar包,需要自己手动打成jar,源码地址:happyfish100
3.fastdfs工具类FastDFSTool
@Slf4j
public class FastDFSTool {
/**
* 上传文件到FastDFS
*
* @param bs
* 文件字节数组
* @param filename
* 文件名
* @return 上传成功后,存放在fastdfs中的文件位置及文件名
* @throws FileNotFoundException
* @throws IOException
* @throws Exception
*/
public static String uploadFile(byte[] bs, String filename)
throws FileNotFoundException, IOException, Exception {
// 获得指定文件所在的classes目录
ClassPathResource classPathResource = new ClassPathResource(
"fdfs_client.conf");
//target\classes\fdfs_client.conf
String path = classPathResource.getFile().getAbsolutePath();
// 将文件对象传入到分布式文件系统中
// 初始化 参数 是配置文件的地址
ClientGlobal.init(path);
// 创建Tracker客户端
TrackerClient trackerClient = new TrackerClient();
// 通过Tracker客户端取得连接获得Tracker服务器端
TrackerServer connection = trackerClient.getConnection();
// Storage客户端
StorageClient1 storageClient1 = new StorageClient1(connection, null);
// 获得文件名称的扩展名
String extension = FilenameUtils.getExtension(filename);
// 上传到fastdfs中,并返回图片的地址
String upload_file1 = storageClient1.upload_file1(bs, extension, null);
return upload_file1;
}
}
4.上传文件:调用工具类即可
@RestController
@RequestMapping("/upload")
public class picController{
@RequestMapping(value = "/uploadpic", method = { RequestMethod.POST })
public String uploadFile(@RequestParam("mpf") MultipartFile mpf)
throws FileNotFoundException, IOException, Exception {
String filename = mpf.getOriginalFilename();
String path= FastDFSTool.uploadFile(mpf.getBytes(), filename);
return ip:port + path;
}
}
5.访问path即可!