Spring Boot使用七牛云

一、引入和配置

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

二、上传文件

java 复制代码
//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;

三、删除文件

java 复制代码
    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;
    }

四、检测文件是否存在

java 复制代码
    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;
    }

五、完整代码

java 复制代码
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;
    }
}

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


相关推荐
SHUIPING_YANG4 分钟前
根据用户id自动切换表查询
java·服务器·数据库
爱吃烤鸡翅的酸菜鱼16 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
惊涛骇浪、22 分钟前
SpringMVC + Tomcat10
java·tomcat·springmvc
墨染点香35 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
ldj20201 小时前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿1 小时前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
风象南1 小时前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端
洛阳泰山1 小时前
Spring Boot 整合 Nacos 实战教程:服务注册发现与配置中心详解
java·spring boot·后端·nacos
Y4090011 小时前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先