FastDFS封装Java工具类并实现文件上传与下载

一、资源准备

1):由于FastDFS客户端jar包并没有在中央仓库中,所以需要使用下列命令手动安装jar包到Maven本地仓库

mvn install:install-file -DgroupId=org.csource.fastdfs -DartifactId=fastdfs  -Dversion=1.2 -Dpackaging=jar -Dfile=F:\fastdfs_client_v1.20.jar

2):pom.xml里加入需要的依赖

<!--fastDFS-->
<dependency>
   <groupId>org.csource.fastdfs</groupId>
   <artifactId>fastdfs</artifactId>
   <version>1.2</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.5</version>
</dependency>
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.2</version>
</dependency>

3):在/resources/config创建配置文件

  • 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=/opt/module/FastDFS/repo/tracker

# tracker_server can ocur more than once, and tracker_server format is
#  "host:port", host can be hostname or ip address
tracker_server=127.0.0.1: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
  • application.properties(Nginx服务器下载地址)
#nginx文件下载地址
FILE_SERVER_URL=http://127.0.0.1:8888/

4):配置spring-mvc.xml文件解析器、并加载application.properties配置文件

<!--引入fastDFS与Nginx整合的服务器地址-->
<context:property-placeholder location="classpath:config/application.properties"/>

<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!--设置默认编码-->
    <property name="defaultEncoding" value="utf-8"/>

    <!--设定文件上传最大值为50MB-->
    <property name="maxUploadSize" value="52428800"/>

    <!--更多参数请自行配置-->
</bean>

二、FastDFS文件上传工具类封装

package com.hf.utils;

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 FastDFSClientUtils {

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

    public FastDFSClientUtils(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);
    }

    /**
     * 功能描述: <br>
     * 〈
     * fastDFS文件上传方法,直接返回文件在FastDFS上的路径(group1/M00/00/00/rBFs1lxlDwGAWLN7AFBHTyw8uXg903.xx)
     * 〉
     *
     * @className: FastDFSClientUtils
     * @author: hf
     * @version: 1.0.0
     * @date: 2019/2/13 17:55
     * @param: [fileName 文件全路径 , extName 文件扩展名(不包含.), metas 文件扩展信息]
     * @return: java.lang.String                                                    ,                                                               java.lang.Integer>
     *
     * History:
     * <author:>          <time:>          <version:>          <desc:>
     */
    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);
    }

    /**
     * 功能描述: <br>
     * 〈
     * fastDFS文件上传方法,直接返回文件在FastDFS上的路径(group1/M00/00/00/rBFs1lxlDwGAWLN7AFBHTyw8uXg903.xx)
     * 〉
     *
     * @className: FastDFSClientUtils
     * @author: hf
     * @version: 1.0.0
     * @date: 2019/2/13 17:56
     * @param: [fileContent 文件的内容(字节数组), extName 文件扩展名,  metas 文件扩展信息]
     * @return: java.lang.String                                                     ,                                                               java.lang.Integer>
     *
     * History:
     * <author:>          <time:>          <version:>          <desc:>
     */
    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);
    }
}

三、文件上传

1): 后台请求处理代码

package com.hf.fastdfs.controller;

import com.hf.utils.FastDFSClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {

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

  /**
   * 功能描述: <br>
   * 〈
   * 文件上传方法
   * 〉
   *
   * @className: UploadController
   * @author: hf
   * @version: 1.0.0
   * @date: 2019/2/13 18:21
   * @param: [file 要上传的文件]
   * @return: java.lang.Object,java.lang.Integer>
   * <p>
   * History:
   * <author:>          <time:>          <version:>          <desc:>
   */
  @PostMapping("/upload")
  public Object upload(MultipartFile file) {
      //获取文件的全名称
      String originalFilename = file.getOriginalFilename();

      //获取文件拓展名
      String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

      try {
          //获得文件上传客户端对象
          FastDFSClientUtils clientUtils = new FastDFSClientUtils("classpath:config/fdfs_client.conf");

          //上传文件至fastDFS服务器
          String fileId = clientUtils.uploadFile(file.getBytes(), extName);

          //获取已上传文件的全路径
          String url = file_server_url + fileId;

          return MsgUtils.success().add("url", url);

      } catch (Exception e) {
          e.printStackTrace();
          return MsgUtils.fail();
      }
  }
}

2): 前端代码(angular发送文件上传请求)

  • angular前端service层
//文件上传服务
app.service('uploadService', function ($http) {
    //上传文件
    this.uploadFile = function () {
        let formData = new FormData();
        //规定文件上传的name属性值必须是file
        formData.append('file', file.files[0]);

        return $http({
            url: '/upload',
            method: 'POST',
            data: formData,
            headers: {'Content-Type': undefined},
            transformRequest: angular.identity
        });
    };
});
  • angular前端controller层
//文件上传前端控制器
app.controller('uploadController', ['$scope', '$http','uploadService', function ($scope, $http, uploadService) {
   
   //文件上传
   $scope.uploadFile = function () {
       uploadService.uploadFile()
           .then(result => {
               //输出返回结果
               console.log(result);
           }, (result) => {
               console.log(result);
           });
   };
}]);

  • index.html
<form role="form" enctype="multipart/form-data">                      
	<div class="form-group">
		<label>选择文件</label>
		<!-- 此处name属性必须是file(前文angular服务层已指定) -->
		<input type="file" class="form-control" name="file">
	</div>
	<button class="btn btn-primary" type="button" ng-click="uploadFile()">开始上传</button>
</form>
  • 效果图
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44187730/article/details/87344052