FastDFS 阿里云OSS配置与使用

1 简介

使用第三方的阿里云OOS来当文件服务器使用,稳定性相对来说比较高,容灾也方便。

官方参考地址:https://help.aliyun.com/product/31815.html?spm=5176.7933691.J_1309819.8.2f1e2a66QAuBQL

2 pom文件配置

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

3 定义配置文件

3.1 新增配置文件

resource下新建配置文件 file.properties

file.endpoint=https://oss-cn-hangzhou.aliyuncs.com
file.accessKeyId=LTA***
file.accessKeySecret=uTv***
file.bucketName=auskat-test
file.objectName=test/images
file.ossHost=auskat-test.oss-cn-beijing.aliyuncs.com/

3.2 解析配置文件

package com.auskat.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * 类文件: FileResource
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/11 0011
 * <p>
 * 时     间: 15:33
 * <p>
 */
@Component
@PropertySource("classpath:file.properties")
@ConfigurationProperties(prefix = "file")
public class FileResource {
    
    

    private String host;

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;

    private String objectName;

    private String ossHost;

    public String getHost() {
    
    
        return host;
    }

    public void setHost(String host) {
    
    
        this.host = host;
    }

    public String getEndpoint() {
    
    
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
    
    
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
    
    
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
    
    
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
    
    
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
    
    
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucketName() {
    
    
        return bucketName;
    }

    public void setBucketName(String bucketName) {
    
    
        this.bucketName = bucketName;
    }

    public String getObjectName() {
    
    
        return objectName;
    }

    public void setObjectName(String objectName) {
    
    
        this.objectName = objectName;
    }

    public String getOssHost() {
    
    
        return ossHost;
    }

    public void setOssHost(String ossHost) {
    
    
        this.ossHost = ossHost;
    }
}

4 测试文件上传

4.1 业务层

FastDFSService

package com.auskat.service;

import org.springframework.web.multipart.MultipartFile;

/**
 * 类文件: FastDFSServer
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/11 0011
 * <p>
 * 时     间: 15:01
 * <p>
 */
public interface FastDFSServer {
    
    

    /**
     * 上传文件到阿里云OSS
     * @param file  文件流
     * @param userId 用户ID(作为文件目录,用来区分文件存储)
     * @param fileExtName 文件后缀名称
     * @return 上传路径
     * @throws Exception 异常信息
     */
    public String uploadOSS(MultipartFile file, String userId, String fileExtName) throws Exception;
}

FastDFSServiceImpl

package com.auskat.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.auskat.config.FileResource;
import com.auskat.service.FastDFSService;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;

/**
 * 类文件: FastDFSServerImpl
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2021/3/11 0011
 * <p>
 * 时     间: 15:02
 * <p>
 */
@Service
public class FastDFSServiceImpl implements FastDFSService {
    
    

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    /**
     * 上传文件到阿里云OSS
     * @param file  文件流
     * @param userId 用户ID(作为文件目录,用来区分文件存储)
     * @param fileExtName 文件后缀名称
     * @return 上传路径
     * @throws Exception 异常信息
     */
    @Override
    public String uploadOSS(MultipartFile file,String fileExtName) throws Exception {
    
    
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = fileResource.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = fileResource.getAccessKeyId();
        String accessKeySecret = fileResource.getAccessKeySecret();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 填写网络流地址。
        InputStream inputStream = new URL("https://www.aliyun.com/").openStream();
        String objectName = fileResource.getObjectName() + "/" + userId + "/" + userId + "." + fileExtName;
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(fileResource.getBucketName(), objectName, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        return objectName;
    }
}

4.2 控制层

FastDFSController

package com.auskat.controller;

import com.auskat.service.FastDFSService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 类文件: FastDFSController
 * <p>
 * <p>
 * 类描述:
 * <p>
 * 作     者: AusKa_T
 * <p>
 * 日     期: 2020/12/7 0007
 * <p>
 * 时     间: 14:46
 * <p>
 */
@RestController
@RequestMapping("fdfs")
public class FastDFSController {
    
    


    @Autowired
    FastDFSService fastDFSService;

		 /**
     * 上传文件到FastDFS
     * @param file 文件流
     * @param request 请求
     * @param response 响应
     * @return 结果
     * @throws Exception 异常信息
     */
     @PostMapping("uploadFile")
    public String uploadFace(
            @RequestParam MultipartFile file,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    

        String path = "";

        // 开始文件上传
        if (file != null) {
    
    
            // 获取文件上传的文件名称
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
    
    
                String[] fileNameArr = fileName.split("\\.");

                // 获取文件的后缀名
                String suffix = fileNameArr[fileNameArr.length - 1];
                String userId = "aaaaaaaa";
                path = fastDFSService.uploadOSS(file, userId,suffix);
                System.out.println(path);
            } 
            return "上传成功!";
        }else {
    
    
            return "文件不能为空! ";
        }
    }

5 相关信息

  • 博文不易,辛苦各位猿友点个关注和赞,感谢

猜你喜欢

转载自blog.csdn.net/qq_15769939/article/details/115193336