分布式文件服务器FastDFS 简单使用

FastDFS 为互联网量身定制,充分考虑了冗余备份、负载均衡、线性扩容等机制,并注重高可用、高性能等指标,使用
FastDFS 很容易搭建一套高性能的文件服务器集群提供文件上传、下载等服务.

FastDFS 架构包括 Tracker server 和 Storage server。客户端请求 Tracker server 进行文件上传、下载,通过 Tracker server 调度最终由 Storage server 完成文件上传和下载。
Tracker server 作用是负载均衡和调度,通过 Tracker server 在文件上传时可以根据一些策略找到 Storage server 提供文件上传服务。可以将 tracker 称为追踪服务器或调度服务器。
Storage server 作用是文件存储,客户端上传的文件最终存储在 Storage 服务器上, Storageserver 没有实现自己的文件系统而是利用操作系统 的文件系统来管理文件。可以将 storage 称为存储服务器。

服务端两个角色:
Tracker:管理集群,tracker 也可以实现集群。每个 tracker 节点地位平等。收集 Storage 集群的状态。
Storage:实际保存文件 Storage 分为多个组,每个组之间保存的文件是不同的。每个组内部可以有多个成员,组成员内部保存的内容是一样的,组成员的地位是一致的,没有主从的概念。

一:文件下载流程

1.安装FastDFS 设置仅主机网段为 25。

2.pom.xml文件依赖引入

<!-- 文件上传组件 --> 
 	 	<dependency> 
 	 	    <groupId>org.csource.fastdfs</groupId> 
 	 	    <artifactId>fastdfs</artifactId> 
 	 	</dependency> 
 	 	<dependency> 
 	 	 	<groupId>commons-fileupload</groupId> 
 	 	 	<artifactId>commons-fileupload</artifactId> 
 	 	</dependency>  

3.FastDFS工具类

package util;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

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);
	}
}

4.springmvc.xml 添加配置:

<!-- 配置多媒体解析器 --> 
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  	 	<property name="defaultEncoding" value="UTF-8"></property> 
 	 	<!-- 设定文件上传的最大值5MB,5*1024*1024 --> 
 	 	<property name="maxUploadSize" value="5242880"></property> 
</bean> 

5.Controller层java代码

/** 
*	文件上传Controller 
*	@author Administrator 
 * 
 */ @RestController 
public class UploadController { 
 	 
 	@Value("${FILE_SERVER_URL}") 
 	private String FILE_SERVER_URL;//文件服务器地址 
 
 	@RequestMapping("/upload") 
 	public Result upload( MultipartFile file){  	 	 	 
 	 	//1、取文件的扩展名 
 	 	String originalFilename = file.getOriginalFilename(); 
 	 	String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); 
 	 	
 	 	try { 
 	 	
//2、创建一个 FastDFS 的客户端 
 	 	 	FastDFSClient fastDFSClient   = new FastDFSClient("classpath:config/fdfs_client.conf"); 
 	 	 	//3、执行上传处理 
 	 	 	String path = fastDFSClient.uploadFile(file.getBytes(), extName); 
 	 	 	
   //4、拼接返回的 url 和 ip 地址,拼装成完整的 url    String url = FILE_SERVER_URL + path;   
    
 	 	 	return new Result(true,url);  	 	
 	 	 	 
 	 	} catch (Exception e) { 
 	 	
 	 	 	e.printStackTrace(); 
 	 	 	return new Result(false, "上传失败"); 
 	 	 	
 	 	}  	 
 	}  
} 

6.service.js代码

//文件上传服务层 
app.service("uploadService",function($http){ 
 	this.uploadFile=function(){ 
 	 	var formData=new FormData(); 
 	    formData.append("file",file.files[0]);    
 	 	return $http({ 
            method:'POST', 
            url:"../upload.do", 
            data: formData, 
            headers: {'Content-Type':undefined}, 
            transformRequest: angular.identity 
        });  	 
 	}  
}); 

anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json。通过设置
‘Content-Type’: undefined,这样浏览器会帮我们把 Content-Type 设置为 multipart/form-data.

通过设置 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化我们的 formdata object.

7.controller.js代码

/** 
 	 * 上传图片 
 	 */ 
 	$scope.uploadFile=function(){    
 	 	uploadService.uploadFile().success(function(response) {          
         if(response.success){//如果上传成功,取出url 
          	$scope.image_entity.url=response.message;//设置文件地址 
         }else{ 
          	alert(response.message); 
         } 
        }).error(function() {            
              alert("上传发生错误"); 
        });         
    };     

(2)修改图片上传窗口,调用上传方法,回显上传图片


(3)修改新建按钮

6.3.3 图片列表
(1) 在 goodsController.js 增加方法
$scope.entity={goods:{},goodsDesc:{itemImages:[]}};//定义页面实体结构
//添加图片列表

   $scope.add_image_entity=function(){      
image_entity
        $scope.entity.goodsDesc.itemImages.push($scope.); 
    } 

(2) 修改上传窗口的保存按钮

<	button	 class="btn btn-success" ng-click="add_image_entity()" data-dismiss="modal"	 
		
aria-hidden="true">保存</	button	> 

(3) 遍历图片列表

<tr ng-repeat="pojo in entity.goodsDesc.itemImages"> 
 	 <td>{{pojo.color}}</td> 
 	 <td><img alt="" src="{{pojo.url}}" width="100px" height="100px"></td> 
 <td><button type="button" class="btn btn-default" title="删除" ><i class="fa fa-trash-o"></i> 删除</button></td> 
</tr> 

6.3.4 移除图片
在 goodsController.js 增加代码
//列表中移除图片

   $scope.remove_image_entity=function(index){ 
         $scope.entity.goodsDesc.itemImages.splice(index,1); 
    } 

修改列表中的删除按钮

<	button	 	type="button" 	class="btn 	btn-default" 	title=" 删 除 "	 
	ng-click="remove_image_entity($index)"><i class="fa fa-trash-o"></i> 删除</	button	> 	
			
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值