java整合fastdfs(单节点)

1.引入依赖

       <dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27-SNAPSHOT</version>
        </dependency>

配置文件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即可!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值