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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值