分布式文件服务器FastDFS之“文件上传后(JAVA),前(AngularJS)端代码"
Posted 记录java路上的小问题
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分布式文件服务器FastDFS之“文件上传后(JAVA),前(AngularJS)端代码"相关的知识,希望对你有一定的参考价值。
FastDFS 是用 c 语言编写的一款开源的分布式文件系统。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称为存储服务器。
FastDFS在linux上的安装步骤太繁琐了,装了好几天才研究出来,但步骤没有保留,大家百度吧!
后端代码
1.工程pom.xml引入依赖
<!-- 文件上传组件 -->
<dependency>
<groupId>org.csource.fastdfs</groupId>
<artifactId>fastdfs</artifactId>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
2.工具类 FastDFSClient.java
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);
}
}
3.配置文件:fdfs_client.conf
# connect timeout in seconds
# default value is 30s
connect_timeout=30
# network timeout in seconds
# default value is 30s
network_timeout=60
# the base path to store log files
base_path=/home/fastdfs
# tracker_server can ocur more than once, and tracker_server format is
# "host:port", host can be hostname or ip address
tracker_server=192.168.25.133:22122
#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info
# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false
# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600
# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false
# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false
# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf
#HTTP settings
http.tracker_server_port=80
#use "#include" directive to include HTTP other settiongs
##include http.conf
3.1添加配置application.properties:
FILE_SERVER_URL=http://192.168.25.133/
3.2添加配置springmvc.xml:
<!-- 配置多媒体解析器-->
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="defaultEncoding"value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<propertyname="maxUploadSize"value="5242880"></property>
</bean>
4.控制层 新建UploadController.java
package com.pinyougou.shop.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import entity.Result;
import util.FastDFSClient;
/**
* 文件上传Controller
* @author Administrator
*
*/
@RestController
publicclassUploadController {
@Value("${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);
String url = FILE_SERVER_URL + path;
returnnew Result(true,url);
} catch (Exception e) {
e.printStackTrace();
returnnew Result(false, "上传失败");
}
}
}
前端代码
1.服务层:uploadService.js
//文件上传服务层
app.service("uploadService",function($http){
this.uploadFile=function(){
//html5中新增的一个类(在文件上传的时候用,代表文件上传二进制数据)
var formData=new FormData();
//file 文件上传框的name, files[0] 取第一个文件上传框
formData.append("file",file.files[0]);
return $http({
method:'POST',
url:"../upload.do",
data: formData,
headers: {'Content-Type':undefined},//上传文件的话必须指定类型,否则默认json类型
transformRequest: angular.identity//对整个表单进行二进制序列化
});
}
});
2.将uploadService服务注入到Controller层中及代码编写
/**
*上传图片
*/
$scope.uploadFile=function(){
uploadService.uploadFile().success(function(response) {
if(response.success){//如果上传成功,取出url
}else{
alert(response.message);
}
}).error(function() {
alert("上传发生错误");
});
};
3.页面引入js、页面表单标签加入Angular控件略!
效果
以上是关于分布式文件服务器FastDFS之“文件上传后(JAVA),前(AngularJS)端代码"的主要内容,如果未能解决你的问题,请参考以下文章