SpringBoot上传图片文件到七牛云

准备工作

maven

pom.xml添加七牛云的sdk依赖

        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.27</version>
        </dependency>

配置项

七牛云上传必要的配置有:accessKey、secretKey、bucket 其中accessKey、secretKey在该网址可查看

portal.qiniu.com/user/key

一、新建存储空间

bucket为你的存储空间名,如下:

实现

application.yml配置

upload:
  qiniu:
    domain: 填你的域名
    access-key: 你的accesskey
    secret-key: 你的secretKey
    bucket: 你的存储空间名,我这里为nnx12138

可以看到我的七牛云上传配置中有domain这项配置,这个配置是七牛云buket的存储域名,在内容管理下,主要用于上传文件成功后把文件访问路径返还回去。

但是这个域名是限时30天使用的,所以你最好绑定一个新的域名。

七牛云上传接口和类

@Component
@ConfigurationProperties(prefix = "upload.qiniu")
@Data
public class QiNiuInitConfig {
    private String domain;

    /**
     * 从下面这个地址中获取accessKey和secretKey
     * https://portal.qiniu.com/user/key
     */
    private String accessKey;

    private String secretKey;

    /**
     * 存储空间名
     */
    private String bucket;

}
package top.lixin.service.impl;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.model.FileInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.lixin.config.properties.QiNiuInitConfig;
import top.lixin.config.properties.UploadProperties;
import top.lixin.service.UploadDocumentService;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.UUID;

/**
 * @program: nnxFirstTestBlog
 * @description: 上传文件到七牛云
 * @author:
 * @create: 2023-12-13 14:38
 **/
@Service
public class QiNiuUploadDocumentServiceImpl implements UploadDocumentService {

    private QiNiuInitConfig properties;

    //构造一个带指定Region对象的配置类
    private Configuration cfg = new Configuration(Region.region2());

    private UploadManager uploadManager = new UploadManager(cfg);

    public QiNiuUploadDocumentServiceImpl(QiNiuInitConfig properties) {
        this.properties = properties;
    }


    @Override
    public String uploadImage(MultipartFile imageFile, HttpServletRequest request) {
        String originalFilename = imageFile.getOriginalFilename();
        // 文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileKey = null;
        try {
            fileKey = calculateMD5(imageFile.getInputStream()) + suffix;
        } catch (IOException e) {
            throw new RuntimeException("文件转md5失败");
        }

        // 计算文件的MD5哈希值
        String fileMD5;
        try {
             fileMD5 = calculateMD5(imageFile.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (isFileExists(properties.getAccessKey(), properties.getSecretKey(), properties.getBucket(), fileMD5)) {
            return properties.getDomain() + fileKey;
        }

        try {
            Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
            String token = auth.uploadToken(properties.getBucket());
            Response response = uploadManager.put(imageFile.getInputStream(), fileKey, token, null, null);
            return properties.getDomain() + fileKey;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "error";
    }

    /**
     * 判断文件是否存在
     * @param accessKey
     * @param secretKey
     * @param bucket
     * @param fileKey
     * @return boolean
     */
    public boolean isFileExists(String accessKey, String secretKey, String bucket, String fileKey) {
        Auth auth = Auth.create(accessKey, secretKey);
        Configuration configuration = new Configuration();
        BucketManager bucketManager = new BucketManager(auth, configuration);

        try {
            FileInfo fileInfo = bucketManager.stat(bucket, fileKey);
            return fileInfo != null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取md5
     * @param inputStream
     * @return {@link String}
     */
    public String calculateMD5(InputStream inputStream) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
            byte[] digest = md.digest();

            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Region配置,这里代表空间的存取区域,因为我的存储空间的区域为华南。所以为Region.region2(),查看自己的存储区域可在空间概览的最下方查看到,这里就不截图了,图片占位太大。
Region对应的设置:

image.png

相关推荐

  1. springboot实现文件下载

    2023-12-14 09:24:04       17 阅读
  2. SpringBoot文件阿里

    2023-12-14 09:24:04       37 阅读
  3. nodejs + vue + element 本地调用图片

    2023-12-14 09:24:04       37 阅读
  4. 使用wangeditor富文本插件,自定义

    2023-12-14 09:24:04       12 阅读
  5. 【华为SpringBoot + OBS 文件

    2023-12-14 09:24:04       43 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-14 09:24:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-14 09:24:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-14 09:24:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-14 09:24:04       20 阅读

热门阅读

  1. QEMU源码全解析 —— virtio(6)

    2023-12-14 09:24:04       47 阅读
  2. Android WebView 响应缓存 笔记

    2023-12-14 09:24:04       44 阅读
  3. 【工具】VUE 前端列表拖拽功能代码

    2023-12-14 09:24:04       44 阅读
  4. 部署Openstack HA

    2023-12-14 09:24:04       33 阅读
  5. 7、无消息丢失配置怎么实现?

    2023-12-14 09:24:04       27 阅读
  6. 文本生成图片 学习笔记

    2023-12-14 09:24:04       43 阅读
  7. Node.js模块化的基本概念和分类及使用方法

    2023-12-14 09:24:04       31 阅读