Spring Boot使用七牛云

本文介绍了如何在SpringBoot应用中使用QiniuJavaSDK进行文件上传、删除以及检查文件是否存在,包括Maven配置、访问令牌生成和使用BucketManager进行操作。
摘要由CSDN通过智能技术生成

一、引入和配置

//maven配置
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.7.0</version>
</dependency>
#七牛云application.yml配置 
qiniu:
    # 配置accessKey
    accessKey: "xxx"
    # 配置secretKey
    secretKey: "xxx"
    # 配置空间名称
    bucket: "xxx"
    # 配置域名
    url: "xxx"

二、上传文件

//1、获取文件上传的流
byte[] fileBytes = multipartFile.getBytes();

//3、获取文件名
String originalFilename = multipartFile.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String filename = "file/" + datePath+"/"+ multipartFile.getOriginalFilename();

//4.构造一个带指定 Region 对象的配置类
//Region.南(根据自己的对象空间的地址选
Configuration cfg = new Configuration(Region.huanan());
UploadManager uploadManager = new UploadManager(cfg);

//5.获取七牛云提供的 token
Auth auth = Auth.create(accessKey, accessSecretKey);
String upToken = auth.uploadToken(bucket, filename);
System.out.println("文件名:" + multipartFile.getOriginalFilename());
Response response = uploadManager.put(fileBytes,filename,upToken);
int code = response.statusCode;

三、删除文件

    public boolean deleteFile(String key)
    {
        try {
            Configuration cfg = new Configuration(Region.huanan());
            BucketManager bucketManager = new BucketManager(Auth.create(accessKey, accessSecretKey), cfg);
            Response response = bucketManager.delete(bucket, key);
            int code = response.statusCode;
            return code == 200 ? true : false;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }

四、检测文件是否存在

    public FileInfo checkFile(String key)
    {
        FileInfo fileInfo = null;
        try {
            Configuration cfg = new Configuration(Region.huanan());
            BucketManager bucketManager = new BucketManager(Auth.create(accessKey, accessSecretKey), cfg);
            fileInfo = bucketManager.stat(bucket, key);
            System.out.println(key);
            System.out.println(fileInfo.status);
        } catch (IOException e) {
            e.getCause();
        }
        return fileInfo;
    }

五、完整代码

package com.xx.file;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.qiniu.storage.BucketManager;

@Component
public class QiniuUtils {

    @Value("${qiniu.accessKey}")
    private String accessKey;      //公钥

    @Value("${qiniu.secretKey}")
    private  String accessSecretKey;   //私钥

    @Value("${qiniu.bucket}")
    private  String bucket;   // 存储空间

    @Value("${qiniu.url}")//# 域名/路径
    private String url;

    /**
     * 上传图片到七牛云
     * @param multipartFile
     * @return
     */
    public JSONObject uploadImageQiniu(MultipartFile multipartFile)
    {
        JSONObject jsonObject = new JSONObject();

        try {
            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();

            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());

            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = "file/" + datePath+"/"+ multipartFile.getOriginalFilename();

            //4.构造一个带指定 Region 对象的配置类
            //Region.南(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.huanan());
            UploadManager uploadManager = new UploadManager(cfg);

            //5.获取七牛云提供的 token
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket, filename);
            System.out.println("文件名:" + multipartFile.getOriginalFilename());
            Response response = uploadManager.put(fileBytes,filename,upToken);
            int code = response.statusCode;

            if (code == 200){
                //jsonObject.put("name", multipartFile.getOriginalFilename());
            } else {
                jsonObject.put("url", "");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return jsonObject;
    }

    /**
     * 删除文件
     * @param key
     * @return
     */
    public boolean deleteFile(String key)
    {
        try {
            Configuration cfg = new Configuration(Region.huanan());
            BucketManager bucketManager = new BucketManager(Auth.create(accessKey, accessSecretKey), cfg);
            Response response = bucketManager.delete(bucket, key);
            int code = response.statusCode;
            return code == 200 ? true : false;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 检测文件是否存在
     * @param key
     * @return
     */
    public FileInfo checkFile(String key)
    {
        FileInfo fileInfo = null;
        try {
            Configuration cfg = new Configuration(Region.huanan());
            BucketManager bucketManager = new BucketManager(Auth.create(accessKey, accessSecretKey), cfg);
            fileInfo = bucketManager.stat(bucket, key);
            System.out.println(key);
            System.out.println(fileInfo.status);
        } catch (IOException e) {
            e.getCause();
        }
        return fileInfo;
    }
}

六、上传同名文件不刷新问题解决

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值