FastDFS基础实例&文件上传实例

更新时间:2019-03-19 11:04:43 点击次数:1406次
FastDFS依赖jar包

<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.1-RELEASE</version>
</dependency>

fdfs_client.conf

connect_timeout=30
network_timeout=60
base_path=/home/fastdfs
tracker_server=192.168.110.130:22122
log_level=info
use_connection_pool = false
connection_pool_max_idle_time = 3600
load_fdfs_parameters_from_tracker=false
use_storage_id = false
storage_ids_filename = storage_ids.conf
http.tracker_server_port=80

public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
//加载配置文件 文件绝对路径
ClientGlobal.init("D:\\eclipse\\ECLIProjects\\FastDFSdemo\\src\\main\\resources\\fdfs_client.conf");
//创建管理客户端
TrackerClient trackerClient = new TrackerClient();
//创建管理服务端 通过管理客户端构建
TrackerServer trackerServer = trackerClient.getConnection();
//创建存储服务端
StorageServer storageServer=null;
//创建存储客户端 通过管理服务端和存储服务端构建
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
//开始上传文件 文件绝对路径 文件上传后的扩展名 文件的扩展信息
String[] strs = storageClient.upload_file("E:\\user\\Pictures\\one.png", "png", null);
//打印file_id
for (String str : strs) {
System.out.println(str);
}
}
}

Console打印

group1
M00/00/00/wKgZhVyM91uAIh1UAABgkhgats8303.png

浏览器输入 http://192.168.110.130/group1/M00/00/00/wKgZhVyM91uAIh1UAABgkhgats8303.png访问图片

文件上传实例
把冗余操作封装到工具类

public class FastDFSClient {

private TrackerClient trackerClient = null;
private TrackerServer trackerServer = null;
private StorageServer storageServer = null;
private StorageClient1 storageClient = null;

public FastDFSClient(String conf) throws Exception {
if (conf.contains("classpath:")) {
conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
}
ClientGlobal.init(conf);
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageServer = null;
storageClient = new StorageClient1(trackerServer, storageServer);
}

/**
* 上传文件方法
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param fileName 文件全路径
* @param extName 文件扩展名 不包含'.'
* @param metas 文件扩展信息
* @return
* @throws Exception
*/
public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
String result = storageClient.upload_file1(fileName, extName, metas);
return result;
}

public String uploadFile(String fileName) throws Exception {
return uploadFile(fileName, null, null);
}

public String uploadFile(String fileName, String extName) throws Exception {
return uploadFile(fileName, extName, null);
}

/**
* 上传文件方法
* <p>Title: uploadFile</p>
* <p>Description: </p>
* @param fileContent 文件的内容 字节数组
* @param extName 文件扩展名
* @param metas 文件扩展信息
* @return
* @throws Exception
*/
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
String result = storageClient.upload_file1(fileContent, extName, metas);
return result;
}

public String uploadFile(byte[] fileContent) throws Exception {
return uploadFile(fileContent, null, null);
}

public String uploadFile(byte[] fileContent, String extName) throws Exception {
return uploadFile(fileContent, extName, null);
}
}

config.properties

FILE_SERVER_URL=http://192.168.110.130/

@RestController
public class UploadController {

@Value("${FILE_SERVER_URL}")
private String fileServerUrl;

@RequestMapping("/upload")
public Result upload(MultipartFile file) {
//获取文件名
String filename = file.getOriginalFilename();
//获取文件后缀名 从最后一个点后一位截取
String extName = filename.substring(filename.lastIndexOf(".")+1);

try {
FastDFSClient client = new FastDFSClient("classpath:fdfs_client.conf");
String fileId = client.uploadFile(file.getBytes(), extName);
String url = fileServerUrl+fileId;//图片完整地址
return new Result(true, url);
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "上传失败");
}
}
}
class Result implements Serializable {
private boolean success;//是否成功
private String message;//返回信息
public Result(boolean success, String message) {
this.success = success;
this.message = message;
}
}

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var app = angular.module('appName', []);

app.service('uploadService', function($http){
//上传文件
this.uploadFile=function(){
var formdata=new FormData();
//选择文件上传框name为file的第一个元素
formdata.append('file', file.files[0]);
//此处使用Angular请求 jQuery与之类似
return $http({
url:'../upload.do',
method:'post',
data:formdata,
headers:{'Content-Type':undefined},
transformRequest:angular.identity
});
}
});

app.controller('ctrlName', function($scope, uploadService){
$scope.imageEntity={};//初始化imageEntity
//上传文件
$scope.uploadFile=function(){
uploadService.uploadFile().success(
function(response){
if (response.success) {
$scope.imageEntity.url=response.message
} else {
alert(response.message);
}
}
);
}
});
</script>
</head>
<body ng-app="appName" ng-controller="ctrlName">
<table>
<tr>
<td>图片</td>
<td>
<table>
<tr>
<td>
<input type="file" id="file" />
<button type="button" ng-click="uploadFile()">
上传
</button>
</td>
<td>
<img ng-src="{{imageEntity.url}}" width="200px" height="200px">
</td>
</tr>
</table>
</td>
</tr>
</table>

<script type="text/javascript">
var editor;
KindEditor.ready(function(K) {
editor = K.create('textarea[name="content"]', {
allowFileManager:true
});
});
</script>
</body>

本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是一个个人学习交流的平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽,造成漏登,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

回到顶部
嘿,我来帮您!