springboot整合七牛云oss---实例一

配置文件

OSS: # 默认为七牛云OSS存储
  # 公钥
  accessKey: 你的公钥
  # 私钥
  secretKey: 你的密钥
  # 存储空间名
  bucketName: cancan7
  # 域名/路径
  path: 你的域名
  # 往空间里存储的文件夹 不需要可以删除
  documentName: testImage/
file:
  # 上传文件允许的扩展名
  allowed: png,jpg,jpeg,pdf,bmp


spring:
  servlet:
    multipart:
      # 单次最大上传
      max-request-size: 20MB
      # 最大文件上传
      max-file-size: 2MB

配置类:

package com.dragonwu.config;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Dragon Wu
 * @since 2022-10-16 13:48
 **/
@Configuration
public class QiniuOSSConfig {
    @Value("${OSS.accessKey}")
    private String accessKey;      //公钥
    @Value("${OSS.secretKey}")
    private String secretKey;   //私钥

    /*
    华东机房
     */
    private com.qiniu.storage.Configuration qnConfig() {
        return new com.qiniu.storage.Configuration(Region.huadong());//根据自己机房的位置来选择
    }

    /*
     构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager() {
        return new UploadManager(qnConfig());
    }

    /*
     认证信息实例
     */
    @Bean
    public Auth auth() {
        return Auth.create(accessKey, secretKey);
    }

    /*
     构建七牛空间管理实例
     */
    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth(), qnConfig());
    }
}

服务层实现

服务接口:

import com.qiniu.storage.model.FileInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Dragon Wu
 * @since 2022-10-15 16:17
 **/
public interface QiniuOSSService {

    /**
     * 上传文件
     *
     * @param file 上传的文件
     * @return key 文件存储的路径
     */
    String uploadFile(MultipartFile file) throws RuntimeException;

    /**
     * 删除文件
     *
     * @param key 文件的key
     * @return 删除成功返回true, 否则返回false
     */
    Boolean deleteFile(String key) throws RuntimeException;

    /**
     * 获取文件访问的路径
     *
     * @param filePath 文件存储的相对路径
     * @return 文件的访问路径
     */
    String getFileAskingPath(String filePath);

    /**
     * 检查文件是否存在于七牛云
     *
     * @param key 文件的key
     * @return 文件信息,若为null代表不存在
     */
    FileInfo checkFile(String key);
}

服务实现类:

import com.dragonwu.service.QiniuOSSService;
import com.dragonwu.util.DateUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;
import java.util.UUID;

/**
 * @author Dragon Wu
 * @since 2022-10-15 16:18
 **/
@Service
public class QiniuOSSServiceImpl implements QiniuOSSService {

    @Autowired
    private Auth auth;

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Value("${OSS.path}")
    private String path;       // 域名
    @Value("${OSS.documentName}")
    private String documentName;   // 空间里的文件夹
    @Value("${file.allowed}")
    private String[] allowed; //图片允许的扩展名
    @Value("${OSS.bucketName}")
    private String bucketName;   // 存储空间

    @Override
    public String uploadFile(MultipartFile file) throws RuntimeException {
        try {
            //获取原始文件名
            String originalFileName = Objects.requireNonNull(file.getOriginalFilename());
            //判断文件是否允许上传
            if (!isFileAllowed(originalFileName)) throw new IllegalArgumentException();
            //生成文件名
            String fileName = getRandomImgName(originalFileName);
            //默认不指定key的情况下,以文件的hash值作为文件名

            byte[] uploadBytes = file.getBytes();
            String upToken = auth.uploadToken(bucketName);
            String key = documentName + DateUtils.getTodayDate() + "/" + fileName;
            uploadManager.put(uploadBytes, key, upToken);

            return key;
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("错误的文件名");
        } catch (Exception e) {
            throw new RuntimeException("文件上传出错");
        }
    }

    @Override
    public Boolean deleteFile(String key) throws RuntimeException {
        if (Objects.isNull(checkFile(key))) {
            return true;
        } else {
            try {
                bucketManager.delete(bucketName, key);
                return true;
            } catch (QiniuException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    @Override
    public FileInfo checkFile(String key) {
        FileInfo fileInfo = null;
        try {
            fileInfo = bucketManager.stat(bucketName, key);
        } catch (QiniuException ignored) {
        }
        return fileInfo;
    }

    @Override
    public String getFileAskingPath(String filePath) {
        return path + "/" + filePath;
    }

    /**
     * 生成唯一图片名称
     *
     * @param fileName 原文件名
     * @return 云服务器fileName
     */
    private static String getRandomImgName(String fileName) throws IllegalArgumentException {
        int index = fileName.lastIndexOf(".");

        if (fileName.isEmpty() || index == -1) {
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index).toLowerCase();
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 拼接新的名称
        return uuid + suffix;
    }

    /**
     * 判断文件是否被允许上传
     *
     * @param fileName 文件名
     * @return 允许true, 否则false
     */
    private boolean isFileAllowed(String fileName) {
        // 获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        for (String allow : allowed) {
            if (allow.equals(suffixName)) {
                return true;
            }
        }
        return false;
    }
}

工具类与控制类

public class DateUtils {

    /**
     * 获取当天日期
     *
     * @return 当天日期
     */
    public static String getTodayDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        return simpleDateFormat.format(new Date());
    }
}
import com.dragonwu.service.QiniuOSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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;

/**
 * @author Dragon Wu
 * @since 2022-10-15 17:09
 **/
@RestController
@RequestMapping("/OSS")
public class QiniuOSSController {

    @Autowired
    private QiniuOSSService qiniuOSSService;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) {
        //上传文件到七牛云服务器
        //把图片放到距离图片最近的服务器上,降低我们自身服务器的带宽消耗
        try {
            return qiniuOSSService.getFileAskingPath(qiniuOSSService.uploadFile(file));
        } catch (RuntimeException e) {
            return e.getMessage();
        }
    }

    @DeleteMapping("/delete")
    public String delete(@RequestParam String key) {
        try {
            return qiniuOSSService.deleteFile(key)?"文件已删除":"删除失败";
        } catch (RuntimeException e) {
            return e.getMessage();
        }
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值