FastDFS上传图片的简单使用
2018-08-31 本文已影响0人
东方舵手
1. 在虚拟机中运行FastDFS
运行FastDFS2. pom文件中添加依赖和引入依赖包
<!-- 添加FastDFS客户端的引用 -->
<dependency>
<groupId>fastdfs_client</groupId>
<artifactId>fastdfs_client</artifactId>
<version>1.25</version>
</dependency>
导入fastdfs_client项目,添加到maven仓库中
导入项目
将项目install到maven中
3. 创建FastDFS的配置文件
配置文件// 内容就是FastDFS服务器地址和端口号
tracker_server=192.168.25.133:22122
4. 简单使用test
@Test
public void uploadFile() throws FileNotFoundException, IOException, MyException {
//1.向工程中添加jar包
//2.创建一个配置文件,配置tracker服务器的地址
//3.加载配置文件
ClientGlobal.init("D:/WorkSpace/project1/taotao-manager-web/src/main/resources/resource/client.conf");
//4.创建一个TrackerClient对象
TrackerClient trackerClient = new TrackerClient();
//5.使用TrackerClient对象获得TrackerServer对象
TrackerServer trackerServer = trackerClient.getConnection();
//6.创建一个StorageServer的引用null就可以
StorageServer storageServer = null;
//7.创建一个StorageClient对象,TrackerServer StorageServer两个参数
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
//8.使用StorageClient对象上传文件
String[] strings = storageClient.upload_file("C:\\Users\\koax\\Pictures\\20180202135447406.png", "png", null);
for (String string : strings) {
System.out.println(string);
}
}
spring中使用
/**
* 图片上传Controller
* @author koax
*/
@Controller
public class PictureController {
//IMAGE_SERVER_URL=http://192.168.25.133/
@Value("${IMAGE_SERVER_URL}")
private String IMAGE_SERVER_URL;
@RequestMapping("/pic/upload")
@ResponseBody
public String picUpload(MultipartFile uploadFile) {
try {
//接收上传的文件
//取扩展名
String originalFilename = uploadFile.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
//上传到图片服务器
FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/client.conf");
String url = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
url = IMAGE_SERVER_URL + url;
//响应上传图片的url
Map result = new HashMap<>();
result.put("error", 0);
result.put("url", url);
return JsonUtils.objectToJson(result);
} catch (Exception e) {
e.printStackTrace();
Map result = new HashMap<>();
result.put("error", 0);
result.put("message", "图片上传失败");
return JsonUtils.objectToJson(result);
}
}
}