准备:一台虚拟机,已经安装了fastDFS,此虚拟机将tracker_server和storage_server安装在了一起。ip为192.168.25.133
第一部分 按照步骤一步一步实现
第一步、导入fastDFS的坐标
<dependency> <groupId>org.csource.fastdfs</groupId> <artifactId>fastdfs</artifactId> <version>1.2</version> </dependency> <!--文件上传组件--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
第二步、编写配置文件
fastDFS的配置文件fast_client.conf全文如下(resources/properties/fdfs_client.conf)
#把此文件放入工程中所需的模块的resources/config目录下,通过FastDFSClient工具类的构造方法加载即可,一般只需修改tracker_server #使用举例,controller #//获取从properties文件中定义的的tracker server的值 # @Value("${FILE_SERVER_URL}") # private String FILE_SERVER_URL; # # @RequestMapping("/uploadFile") # public Result uploadFile(MultipartFile file) { # try { # String originalFilename = file.getOriginalFilename(); # String extName = originalFilename.substring(originalFilename.indexOf(".") + 1); # # FastDFSClient fastDFSClient = new FastDFSClient("classpath:/config/fdfs_client.conf"); # String s = fastDFSClient.uploadFile(file.getBytes(), extName); # return new Result(true, FILE_SERVER_URL + s); # } catch (Exception e) { # return new Result(false, "upload failed!"); # } # } # 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
将上方的tracker_server的属性更改为自己的主机ip【我的是192.168.25.133:22122】
# tracker_server can ocur more than once, and tracker_server format is
# "host:port", host can be hostname or ip address,修改成自己tracker_server的ip地址和端口号,默认22122
tracker_server=192.168.25.133:22122
第三步、代码测试(原生代码,没有使用自定义工具类FastDFSClient)
将本地目录的F:\image\01.jpg文件上传至服务器
public class fastDFSDemo { public static void main(String[] args) throws Exception { // 1、 加载配置文件, 配置文件中的内容就是 tracker 服务的地址。 ClientGlobal.init("F:\coding\helloFastDFS\src\main\resources\fdfs_client.conf"); // 2、 创建一个 TrackerClient 对象。 直接 new 一个。 TrackerClient trackerClient=new TrackerClient(); // 3、 使用 TrackerClient 对象创建连接, 获得一个 TrackerServer 对象。 TrackerServer trackerServer = trackerClient.getConnection(); // 4、 创建一个 StorageServer 的引用, 值为 null StorageServer storageServer=null; // 5、 创建一个 StorageClient 对象, 需要两个参数 TrackerServer 对象、 StorageServer的引用 StorageClient1 storageClient1=new StorageClient1(trackerServer,storageServer); // 6、 使用 StorageClient 对象上传图片。 String[] strings = storageClient1.upload_appender_file("F:\image\01.jpg","jpg", null); // 7、 返回数组。 包含组名和图片的路径。 for (String string : strings) { System.out.println(string); } } }
运行结果
group1
M00/00/00/wKgZhV0p3meEboMrAAAAAOo7as0657.jpg
第四步、访问该图片,测试结果
图片的加载是依赖于negix加载的,默认端口号80,访问路径如下
http://192.168.25.133/group1/M00/00/00/wKgZhV0p3AqESvEmAAAAAOo7as0348.jpg
第二部分 抽取出工具类,并通过spring在网页端上传实现
第一步、导入坐标
略
第二步、在springMVC中配置该框架的多部件解析器
不配置的话会在文件上传的时候抛出无法解析的异常。
<!--文件上传的多媒体解析器 主要配置:限制文件大小 配置字符集编码--> <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>
第三步、将第一部分中的通用代码封装成fastDFS文件上传的工具类
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); } }
第四步、编写SpringMVC的文件上传Controller,用于接收从网页发送的文件上传请求,我们起名为UpLoadController,返回的Result是一个自定义的工具类
@RestController @RequestMapping("/upload") public class UploadController { @Value("${FILE_SERVER_URL}") private String FILE_SERVER_URL; @RequestMapping("/uploadFile") public Result uploadFile(MultipartFile file) { try { String originalFilename = file.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.indexOf(".") + 1); FastDFSClient fastDFSClient = new FastDFSClient("classpath:/config/fdfs_client.conf"); String s = fastDFSClient.uploadFile(file.getBytes(), extName); return new Result(true, FILE_SERVER_URL + s); } catch (Exception e) { return new Result(false, "upload failed!"); } } }
第五步、在配置SpringMVC中的配置文件,加载一个文件
<context:property-placeholder location="classpath:config/application.properties"/> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json"/> <property name="features"> <array> <value>WriteMapNullValue</value> <value>WriteDateUseDateFormat</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
第六步、编写上方加载的文件,该文件为tracker_server的主机信息文件application.properties
FILE_SERVER_URL=http://192.168.25.133/
第七步、编写前端界面,要求前端界面的请求表单form的方式method必须为post,加密类型enctype必须为multipart/data-form,必须有个buttom的type为file
以angularJS为例实现前端文件上传的代码
前端页面
<input type="file" id="file" /><br/>
<button ng-click="uploadFile()" class="btn btn-primary" type="button" >上传</button><br/>
<img src="{{entity.pic}}" width="200px" height="100px">
controller中被调用的方法
$scope.entity = {}; $scope.uploadFile = function () { uploadService.uploadFile().success( function (response) { $scope.entity.pic = response.message; } ) }
uploadService中的方法
//服务层 app.service('uploadService',function($http){ //文件上传 this.uploadFile=function(){ //基于angularjs结合html5(FormData)完成文件上传 <form> var formData = new FormData(); //要基于定义的表单数据对象,获取页面选择的文件对象 //参数一:与后台java代码接收文件对象的参数名一致 //参数二:获取页面的文件对象 file.files[0] file与<input type="file" id="file" />中的id保存一致 formData.append("file",file.files[0]); return $http({ url: "../upload/uploadFile.do", method:"post", data:formData, headers : {'Content-Type' : undefined}, //上传文件必须是这个类型,默认text/plain,相当于配置了enctype="multipart/form-data" transformRequest : angular.identity //对整个表单进行二进制序列化 }); } });