分佈式文件系統-FastDFS+阿里OSS

分佈式文件系統-FastDFS+阿里OSS


一、配置FastDFS環境準備工作

1.1、環境準備

  • Centos7.x兩臺,分別安裝tracker與storage

  • 下載安裝包:

    • libfastcommon:FastDFS分離出的一些公用函數包
    • FastDFS:FastDFS本體
    • fastdfs-nginx-module:FastDFS和nginx的關聯模塊
    • nginx:發佈訪問服務

安裝包的下載地址:https://github.com/happyfish100
官方安裝過程:https://github.com/happyfish100/fastdfs/wiki

1.2、安裝步驟(tracker虛擬機與storage虛擬機都要安裝)

1.2.1、安裝基礎庫

yum install -y gcc gcc-c++
yum -y install libevent

1.2.2、安裝libfastcommon函數庫

# 解壓
tar -zxvf libfastcommon-1.0.42.tar.gz
  • 進入libfastcommon文件夾,編譯並且安裝

    ./make.sh
    ./make.sh install
    

    安裝的目錄從控制檯可以看見

1.2.3、安裝fastdfs主程序文件

# 解壓
tar -zxvf fastdfs-6.04.tar.gz
  • 進入到fastdfs目錄,查看fastdfs安裝配置

    cd fastdfs-6.0.04/
    vim make.sh
    
    TARGET_PREFIX+$DESTDIR/usr
    TARGET_CONF_PATH=$DESTDIR/etc/fdfs
    TARGET_INIT_PATH=$/DESTDIR/etc/init.d
    
  • 安裝fastdfs

    ./make.sh
    ./make.sh install
    

1.2.4、拷貝配置文件到/etc/fdfs中

  • 進入fastdfs/conf目錄

    cd fastdfs-6.0.04/conf
    
  • 拷貝配置文件

    cp * /etc/fdfs
    

二、配置tracker服務

  • tracker和storage都是同一個fastdfs的主程序的兩個不同概念,配置不同的配置文件就可以設定爲tracker或者storage

2.1、配置tracker

  • /etc/fdfs下都是一些配置文件,配置tracker即可

    vim tracker.config
    
  • 修改tracker配置文件,此爲tracker的工作目錄,保存數據以及日誌

    base_path=/usr/local/fastdfs/tracker
    
    mkdir /usr/local/fastdfs/tracker -p
    

2.2、啓動tracker服務

/usr/bin/fdfs_trackerd /etc/fdfs/tracker.conf
  • 檢查進程

    ps -ef|grep tracker
    
  • 停止tracker

    /usr/bin/stop.sh /etc/fdfs/tracker.conf
    

三、配置Storage服務

3.1、修改storage配置文件

# 修改組名(任意)
group_name=zzm
# 修改storage的工作空間
base_path=/usr/local/fastdfs/storage
# 修改storage的存儲空間
store_path0=/usr/local/fastdfs/storage
# 修改tracker的地址和端口號,用於心跳
tracker_server=192.168.64.137:22122

# 後續結合nginx的一個對外服務端口號
http.server_port=8888
  • 創建目錄

    mkdir /usr/local/fastdfs/storeage -p
    

3.2、啓動storage

/usr/bin/fdfs_storaged /etc/fdfs/storage.conf

前提:必須首先啓動tracker

  • 檢查進程

    ps -ef|grep storage
    

3.3、測試上傳

3.3.1、修改client配置文件

base_path=/usr/local/fastdfs/client
tracker_server=192.168.64.137:22122

3.3.2、創建目錄

mkdir /usr/local/fastdfs/client -p

3.3.3、測試文件上傳

/usr/bin/fdfs_test /etc/fdfs/client.conf upload logo.jpg

logo.jpg爲上傳的圖片資源

四、配置nginx fastdfs 實現文件服務器

  • fastdfs安裝號以後是無法通過http訪問的,這個時候就需要藉助nginx了,所有需要安裝fastddfs的第三方模塊到nginx,就能使用了

:nginx需要和storage在同一個節點

4.1、安裝nginx插件

4.1.1、解壓nginx的fastdfs解壓包

tar -zxvf fastdfs-nginx-module-1.22.tar.gz

4.1.2、複製配置文件到指定位置

cd fastdfs-nginx-module-1.22/src

cp mod_fastdfs.conf /etc/fdfs

4.1.3、修改fastdfs-nginx-module/src/config文件

  • 主要是修改路徑,把local刪除,因爲fastdfs安裝的時候沒有修改路徑,原路徑是/usr/include
vim config
ngx_module_incs="/usr/include"
CORE_INCS="$CORE_INCS /usr/include"

4.2、安裝nginx

  • 安裝步驟沒有區別,唯一區別是,創建makefile文件命令,命令如下
./configure \
--prefix=/usr/local/nginx \
--pid-path=/var/run/nginx/nginx.pid \
--lock-path=/var/locak/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--http-client-body-temp-path=/var/temp/nginx/client \
--http-proxy-temp-path=/var/temp/nginx/proxy \
--http-fastcgi-temp-path=/var/temp/nginx/fastcgi \
--http-uwsgi-temp-path=/var/temp/nginx/uwsgi \
--http-scgi-temp-path=/var/temp/nginx/scgi
--add-module=/home/software/FastDFS/fastdfs-nginx-module-1.22/src

4.3、配置mod_fastdfs.conf

cd /etc/fdfs/
vim mod_fastdfs.conf
  • 修改內容如下

    base_path=/usr/local/fastdfs/tmp
    tracker_server=192.168.64.137:22122
    group_name=zzm
    url_have_group_name=true
    store_path0=/usr/local/fastdfs/tmp
    
  • 創建目錄

    mkdir /usr/local/fastdfs/tmp -p
    

4.4、配置nginx的nginx.conf配置文件

  • 配置文件內容如下

    #user  nobody;
    worker_processes  1;
    
    events {
        worker_connections  1024;
    }
    
    
    http {
        include       mime.types;
        default_type  application/octet-stream;
    
        sendfile        on;
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65;
    
        #gzip  on;
    
        server {
            listen       8888;
            server_name  localhost;
    
            location /zzm/M00 {
                    ngx_fastdfs_module;
            }
    
        }
    
    }
    
  • 啓動

    cd /usr/local/nginx/sbin
    
    ./nginx
    

4.5、資源訪問

  • 訪問之前測試上傳的logo.jpg

    cd /usr/local/fastdfs/storage/data/00/00
    
  • 查看上傳的圖片名稱,然後瀏覽器訪問如下地址

    http://192.168.64.138:8888/zzm/M00/00/00/wKhAil6MNNuAfIG3AABGpXU6GsA963.jpg
    

如何訪問不了,關閉防火牆,兩臺服務器防火牆都要關閉

五、FastDFS整合SpringBoot

  • 創建springboot工程,不會的網上搜一下

5.1、pom.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <artifactId>eat_shop-dev</artifactId>
        <groupId>com.zzm</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eat_shop-dev-fs</artifactId>

    <dependencies>

        <dependency>
            <groupId>com.zzm</groupId>
            <artifactId>eat_shop-dev-service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

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

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.8.0</version>
        </dependency>

    </dependencies>

</project>

5.2、配置文件

  • application.yml配置文件

    server:
      port: 8086
    #########################################################################
    #
    # 配置數據源信息
    #
    #########################################################################
    spring:
      datasource:                                     # 數據源的相關配置
        type: com.zaxxer.hikari.HikariDataSource      # 數據源類型:HikariCP
        driver-class-name: com.mysql.cj.jdbc.Driver    # mysql驅動
        url: jdbc:mysql://127.0.0.1:3306/eat_shop?useSSL=false&serverTimezone=UTC
        username: root
        password: 你的密碼
        hikari:
          connection-timeout: 30000            # 等待連接池分配連接的最大時長(毫秒),超過這個時長還沒可用的連接則發生SQLException,默認:30秒
          minimum-idle: 5                      # 最小連接
          maximum-pool-size: 20               # 最大連接
          auto-commit: true                   # 自動提交
          idle-timeout: 600000                # 連接超時的最大時長(毫秒),超時則被釋放(retired),默認:10分鐘
          pool-name: DateSourceHikariCP       # 連接池名字
          max-lifetime: 1800000              #  連接的生命時長(毫秒),超時而且沒被使用則被釋放,默認:30分鐘
          connection-test-query: SELECT 1
      redis:
        database: 1
        host: 你的ip
        port: 6379
        password: 你的密碼
      servlet:
        multipart:
          max-file-size: 512000 # 文件上傳大小限制爲500kb = 500 * 1024
          max-request-size: 512000 # 請求大小限制爲500kb
    
    #########################################################################
    #
    # mybatis 配置
    #
    #########################################################################
    mybatis:
      type-aliases-package: com.zzm.pojo            # 所有POJO類所在包路徑
      mapper-locations: classpath:mapper/*.xml      # mapper映射文件
      # configuration:
      #  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    
    #########################################################################
    #
    # mybatis mapper配置
    #
    #########################################################################
    mapper:
      mappers: com.zzm.my.mapper.MyMapper
      not-empty: false
      identity: MYSQL
    #分頁插件配置
    pagehelper:
      helper-dialect: mysql
      support-methods-arguments: true
    
    #########################################################################
    #
    # fdfs 配置
    #
    #########################################################################
    fdfs:
      connect-timeout: 5000 # 連接的超時時間
      so-timeout: 5000 # 讀取的超時時間
      tracker-list: 192.168.64.137:22122 # tracker服務所在的ip地址和端口號
    
    
  • file.properties配置文件

    file.host=http://192.168.64.138:8888/
    

5.3、解決跨域

  • 創建CorsConfig.java文件,代碼如下

    package com.zzm.fs.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    
    @Configuration
    public class CorsConfig {
    
        public CorsConfig() {
        }
    
        @Bean
        public CorsFilter corsFilter() {
            // 1. 添加cors配置信息
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedOrigin("http://localhost:8888");
            config.addAllowedOrigin("http://localhost:8080");
            config.addAllowedOrigin("*");
    
            // 設置是否發送cookie信息
            config.setAllowCredentials(true);
    
            // 設置允許請求的方式
            config.addAllowedMethod("*");
    
            // 設置允許的header
            config.addAllowedHeader("*");
    
            // 2. 爲url添加映射路徑
            UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
            corsSource.registerCorsConfiguration("/**", config);
    
            // 3. 返回重新定義好的corsSource
            return new CorsFilter(corsSource);
        }
    
    }
    
    

5.4、構建service層

  • FdfsService.java代碼如下

    package com.zzm.fs.service.impl;
    
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.github.tobato.fastdfs.domain.fdfs.StorePath;
    import com.github.tobato.fastdfs.service.FastFileStorageClient;
    import com.zzm.fs.resourse.FileResourse;
    import com.zzm.fs.service.FdfsService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    
    @Service
    public class FdfsServiceImpl implements FdfsService {
    
        @Autowired
        private FileResourse fileResourse;
    
        @Autowired
        private FastFileStorageClient fastFileStorageClient;
    
        @Override
        public String upload(MultipartFile file, String fileExtName) {
            try {
                StorePath storePath = fastFileStorageClient.uploadFile(
                        file.getInputStream(),
                        file.getSize(),
                        fileExtName,
                        null);
    
                String fullPath = storePath.getFullPath();
    
                return fullPath;
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return null;
        }
     }
    

5.5、構建controller層

  • FdfsController.java代碼如下
package com.zzm.fs.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzm.fs.resourse.FileResourse;
import com.zzm.fs.service.FdfsService;
import com.zzm.pojo.Users;
import com.zzm.pojo.vo.UsersVO;
import com.zzm.service.center.CenterUserService;
import com.zzm.utils.CookieUtils;
import com.zzm.utils.JSONResult;
import com.zzm.utils.JsonUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/fdfs")
public class FdfsController{

    @Autowired
    private FdfsService fdfsService;

    @Autowired
    private FileResourse fileResourse;

    @Autowired
    private CenterUserService centerUserService;

    @ApiOperation(value = "用戶頭像修改", notes = "用戶頭像修改", httpMethod = "POST")
    @PostMapping("/uploadFace")
    public JSONResult uploadFace(
            @ApiParam(name= "userId", value = "用戶id", required = true)
            @RequestParam String userId,
            @ApiParam(name = "file", value = "用戶頭像", required = true)
                    MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response){

        String path = "";


        // 開始文件上傳
        if(file != null){
            try {

                // 獲得文件上傳的文件名稱
                String fileName = file.getOriginalFilename();

                if (StringUtils.isNotBlank(fileName)){

                    // 文件重命名 abc-face.png -> ["abc-face", "png"]
                    String fileNameArr[] = fileName.split("\\.");

                    // 獲取文件的後綴名
                    String suffix = fileNameArr[fileNameArr.length - 1];

                    if (!suffix.equalsIgnoreCase("png") &&
                            !suffix.equalsIgnoreCase("jpg") &&
                            !suffix.equalsIgnoreCase("jpeg")){
                        return JSONResult.errorMsg("上傳圖片格式錯誤");
                    }


                    path = fdfsService.upload(file, suffix);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return JSONResult.errorMsg("上傳的文件不能爲空");
        }

        if (StringUtils.isNotBlank(path)){

            // 由於瀏覽器可能存在緩存的情況,所以在這裏,需要加上時間戳來保證更新後的圖片可以及時刷新
            String finalUserFaceUrl = fileResourse.getHost() + path;

                    // 更新用戶頭像到數據庫
            Users user = centerUserService.updateUserFace(userId, finalUserFaceUrl);


            return JSONResult.ok(user);

        }else{
            return JSONResult.errorMsg("上傳的文件不能爲空");
        }

    }
}

5.6、構建resourse層

  • FileResource.java代碼如下

    package com.zzm.fs.resourse;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    @Component
    @PropertySource("classpath:file.properties")
    @ConfigurationProperties(prefix = "file")
    @Data
    public class FileResourse {
    
        private String host;
    
    }
    

六、阿里OSS整合SpringBoot

  • 去阿里網站申請阿里oss並創建BucketsAccess Key
    在這裏插入圖片描述

6.1、獲取重要參數

  • endpoint
  • accessKeyId
  • accessKeySecret
  • bucketName:你創建bucketName的名稱
  • objectName:你保存文件的路徑
  • ossHost
    在這裏插入圖片描述
    在這裏插入圖片描述

6.2、pom.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <artifactId>eat_shop-dev</artifactId>
        <groupId>com.zzm</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>eat_shop-dev-fs</artifactId>

    <dependencies>

        <dependency>
            <groupId>com.zzm</groupId>
            <artifactId>eat_shop-dev-service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.8.0</version>
        </dependency>

    </dependencies>

</project>

6.3、配置文件

  • application.yml配置文件

    server:
      port: 8086
    #########################################################################
    #
    # 配置數據源信息
    #
    #########################################################################
    spring:
      datasource:                                     # 數據源的相關配置
        type: com.zaxxer.hikari.HikariDataSource      # 數據源類型:HikariCP
        driver-class-name: com.mysql.cj.jdbc.Driver    # mysql驅動
        url: jdbc:mysql://127.0.0.1:3306/eat_shop?useSSL=false&serverTimezone=UTC
        username: root
        password: 你的密碼
        hikari:
          connection-timeout: 30000            # 等待連接池分配連接的最大時長(毫秒),超過這個時長還沒可用的連接則發生SQLException,默認:30秒
          minimum-idle: 5                      # 最小連接
          maximum-pool-size: 20               # 最大連接
          auto-commit: true                   # 自動提交
          idle-timeout: 600000                # 連接超時的最大時長(毫秒),超時則被釋放(retired),默認:10分鐘
          pool-name: DateSourceHikariCP       # 連接池名字
          max-lifetime: 1800000              #  連接的生命時長(毫秒),超時而且沒被使用則被釋放,默認:30分鐘
          connection-test-query: SELECT 1
      redis:
        database: 1
        host: 你的ip
        port: 6379
        password: 你的密碼
      servlet:
        multipart:
          max-file-size: 512000 # 文件上傳大小限制爲500kb = 500 * 1024
          max-request-size: 512000 # 請求大小限制爲500kb
    
    #########################################################################
    #
    # mybatis 配置
    #
    #########################################################################
    mybatis:
      type-aliases-package: com.zzm.pojo            # 所有POJO類所在包路徑
      mapper-locations: classpath:mapper/*.xml      # mapper映射文件
      # configuration:
      #  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    
    #########################################################################
    #
    # mybatis mapper配置
    #
    #########################################################################
    mapper:
      mappers: com.zzm.my.mapper.MyMapper
      not-empty: false
      identity: MYSQL
    #分頁插件配置
    pagehelper:
      helper-dialect: mysql
      support-methods-arguments: true
    
    
    
  • file.properties配置文件

    file.endpoint=http://oss-cn-beijing....
    file.accessKeyId=LTAI4FvqK2f...
    file.accessKeySecret=AtqZfc3oY9vEIU...
    file.bucketName=eatshop
    file.objectName=images
    file.ossHost=https://eatshop.oss-cn-beijing....
    

6.4、解決跨域

  • 創建CorsConfig.java文件,代碼如下

    package com.zzm.fs.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    
    @Configuration
    public class CorsConfig {
    
        public CorsConfig() {
        }
    
        @Bean
        public CorsFilter corsFilter() {
            // 1. 添加cors配置信息
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedOrigin("http://localhost:8888");
            config.addAllowedOrigin("http://localhost:8080");
            config.addAllowedOrigin("*");
    
            // 設置是否發送cookie信息
            config.setAllowCredentials(true);
    
            // 設置允許請求的方式
            config.addAllowedMethod("*");
    
            // 設置允許的header
            config.addAllowedHeader("*");
    
            // 2. 爲url添加映射路徑
            UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
            corsSource.registerCorsConfiguration("/**", config);
    
            // 3. 返回重新定義好的corsSource
            return new CorsFilter(corsSource);
        }
    
    }
    
    

6.5、構建service層

  • FdfsServiceImpl.java代碼如下

    package com.zzm.fs.service.impl;
    
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.github.tobato.fastdfs.domain.fdfs.StorePath;
    import com.github.tobato.fastdfs.service.FastFileStorageClient;
    import com.zzm.fs.resourse.FileResourse;
    import com.zzm.fs.service.FdfsService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    
    @Service
    public class FdfsServiceImpl implements FdfsService {
    
        @Autowired
        private FileResourse fileResourse;
    
        @Override
        public String uploadOSS(MultipartFile file, String userId, String fileExtName) {
    
            // Endpoint以杭州爲例,其它Region請按實際情況填寫。
            String endpoint = fileResourse.getEndpoint();
            // 阿里雲主賬號AccessKey擁有所有API的訪問權限,風險很高。強烈建議您創建並使用RAM賬號進行API訪問或日常運維,請登錄 https://ram.console.aliyun.com 創建RAM賬號。
            String accessKeyId = fileResourse.getAccessKeyId();
            String accessKeySecret = fileResourse.getAccessKeySecret();
            String myObjectName = fileResourse.getObjectName() + "/" + userId + "/" + userId + "." + fileExtName;
            OSS ossClient = null;
    
            try {
                // 創建OSSClient實例。
                ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
                // 上傳網絡流。
                InputStream inputStream = file.getInputStream();
                ossClient.putObject(fileResourse.getBucketName(), myObjectName, inputStream);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            // 關閉OSSClient。
            ossClient.shutdown();
    
            return myObjectName;
        }
    }
    
    

6.6、構建controller層

  • FdfsController.java代碼如下
package com.zzm.fs.controller;

import com.alibaba.fastjson.JSONObject;
import com.zzm.fs.resourse.FileResourse;
import com.zzm.fs.service.FdfsService;
import com.zzm.pojo.Users;
import com.zzm.pojo.vo.UsersVO;
import com.zzm.service.center.CenterUserService;
import com.zzm.utils.CookieUtils;
import com.zzm.utils.JSONResult;
import com.zzm.utils.JsonUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/fdfs")
public class FdfsController extends BaseController{

    @Autowired
    private FdfsService fdfsService;

    @Autowired
    private FileResourse fileResourse;

    @Autowired
    private CenterUserService centerUserService;

    @ApiOperation(value = "用戶頭像修改", notes = "用戶頭像修改", httpMethod = "POST")
    @PostMapping("/uploadFace")
    public JSONResult uploadFace(
            @ApiParam(name= "userId", value = "用戶id", required = true)
            @RequestParam String userId,
            @ApiParam(name = "file", value = "用戶頭像", required = true)
                    MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response){

        String path = "";


        // 開始文件上傳
        if(file != null){
            try {

                // 獲得文件上傳的文件名稱
                String fileName = file.getOriginalFilename();

                if (StringUtils.isNotBlank(fileName)){

                    // 文件重命名 abc-face.png -> ["abc-face", "png"]
                    String fileNameArr[] = fileName.split("\\.");

                    // 獲取文件的後綴名
                    String suffix = fileNameArr[fileNameArr.length - 1];

                    if (!suffix.equalsIgnoreCase("png") &&
                            !suffix.equalsIgnoreCase("jpg") &&
                            !suffix.equalsIgnoreCase("jpeg")){
                        return JSONResult.errorMsg("上傳圖片格式錯誤");
                    }

                    path = fdfsService.uploadOSS(file, userId, suffix);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return JSONResult.errorMsg("上傳的文件不能爲空");
        }

        if (StringUtils.isNotBlank(path)){

            // 由於瀏覽器可能存在緩存的情況,所以在這裏,需要加上時間戳來保證更新後的圖片可以及時刷新
            String finalUserFaceUrl = fileResourse.getOssHost() + path;

                    // 更新用戶頭像到數據庫
            Users user = centerUserService.updateUserFace(userId, finalUserFaceUrl);


            return JSONResult.ok(user);

        }else{
            return JSONResult.errorMsg("上傳的文件不能爲空");
        }

    }
}

6.7、構建resourse層

  • FileResource.java代碼如下

    package com.zzm.fs.resourse;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    @Component
    @PropertySource("classpath:file.properties")
    @ConfigurationProperties(prefix = "file")
    @Data
    public class FileResourse {
    
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
        private String objectName;
        private String ossHost;
    
    }
    
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章