使用fastDFS上传和下载图片文件


package com.xuecheng.test.fastdfs;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* @author newcityman
* @date 2020/2/16 - 15:01
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestFastDFS {
//上传文件
@Test
public void testUpload(){
try {
//加载fastdfs-client.properties配置文件
ClientGlobal.initByProperties("config/fastdfs_client.properties");
//定义TrackerClient,用于请求Tracker
TrackerClient trackerClient = new TrackerClient();
//连接Tracker
TrackerServer trackerServer = trackerClient.getConnection();
//获取Storage服务器
StorageServer storageServer= trackerClient.getStoreStorage(trackerServer);
//创建一个StorageClient
StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);
//向storage服务器上传文件
String filePath="h:/wx_cz.jpg";
String fileId = storageClient1.upload_file1(filePath, "jpg", null);
System.out.println(fileId);
//group1/M00/00/00/wKgAaV5JY7CAGDfKAAAjb9XlGuI005.jpg
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}

//下载文件
@Test
public void testDownload(){
try {
//加载fastdfs-client.properties配置文件
ClientGlobal.initByProperties("config/fastdfs_client.properties");
//定义TrackerClient,用于请求Tracker
TrackerClient trackerClient = new TrackerClient();
//连接Tracker
TrackerServer trackerServer = trackerClient.getConnection();
//获取Storage服务器
StorageServer storageServer= trackerClient.getStoreStorage(trackerServer);
//创建一个StorageClient
StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);
//下载文件
//文件id
String fileId="group1/M00/00/00/wKgAaV5JY7CAGDfKAAAjb9XlGuI005.jpg";
byte[] bytes = storageClient1.download_file1(fileId);
//使用输出流保存文件
FileOutputStream fileOutputStream = new FileOutputStream(new File("i:/lg.jpg"));
fileOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}

}

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM