使用Java实现七牛云OSS云存储上传图片至指定目录

本文介绍了如何使用Java实现通过Controller调用七牛云OSS上传图片,涉及Controller中的文件处理、工具类QnOssUtil中的上传逻辑以及使用配置类QnOssProperties管理七牛云的认证信息。
摘要由CSDN通过智能技术生成

使用Java实现七牛云OSS云存储上传图片至指定目录

思路介绍

首先介绍下我的实现思路,前端通过Controller调用上传方法,上传方法中主要调用了一个七牛云的上传文件的相关代码封装的一个工具类,该工具类中的bucketName、keyId、secret等需要的固定信息是通过yaml配置文件设置的,为了读取该文件的配置信息,我把它封装为了一个名为QnOssProperties的java对象进行使用。

开始前先导入依赖别忘了,基本都是在qiniu的包下的类,爆红先检查这一项。
官方文档

Controller代码

在Controller中,我对获取的文件做了一个文件重命名,同时还指定了一个img文件夹路径,如果你存在根目录可不做此操作。这个地方的斜杠方向不能反。


@Slf4j
@Api(tags = "公共服务相关接口")
@RestController
@RequestMapping("/admin/common")
public class CommonController {
    @Autowired
    QnOssUtil qnOssUtil;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        //获取文件类型,文件名后缀,如.png
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.lastIndexOf("."));

        //生成随机文件名
        fileName = UUID.randomUUID().toString()+fileName;

        //这里额外指定了上传到服务器的哪个目录
        fileName = "img/" + fileName;

        //上传文件
        String path = null;
        try {
            byte[] bytes = file.getBytes();
            path = qnOssUtil.bytesUpload(bytes, fileName);

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

        return Result.success(path);
    }
}

Util工具类代码

这里基本上是七牛的sdk文档中的示例代码,我做了一点改动和注释。

package com.sky.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.sky.properties.QnOssProperties;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Component
@AllArgsConstructor
public class QnOssUtil {
    private QnOssProperties qnOssProperties;

    /**
     * 本地上传
     * @param localFilePath  文件地址绝对路径
     * @return
     */
    public String localUpload(String localFilePath,String fileName) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huadongZheJiang2());   //选择服务器所在的区

        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传
        String accessKey = qnOssProperties.getAccessKeyId();
        String secretKey = qnOssProperties.getAccessKeySecret();
        String bucket = qnOssProperties.getBucketName();
        //如果是Windows情况下,格式是 D:\\qiniu\\test.png
        // String localFilePath = "/home/qiniu/test.png";
        //本地文件绝对路径
        // localFilePath = "C:\\Users\\xyhk\\Downloads\\Snipaste_2023-08-02_15-46-43.png";

        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = fileName;       //指定上传至Oss服务器文件名称,使用\分隔还能指定目录
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return "http://"+qnOssProperties.getEndpoint()+"/"+putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        return null;
    }


    /**
     * 通过文件的字节数组上传
     * @return
     */
    public String bytesUpload(byte[] uploadBytes,String fileName){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huadongZheJiang2());       //选择服务器所在的区
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传
        String accessKey = qnOssProperties.getAccessKeyId();
        String secretKey = qnOssProperties.getAccessKeySecret();
        String bucket = qnOssProperties.getBucketName();
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = fileName;
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://"+qnOssProperties.getEndpoint()+"/"+putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return null;
    }
}

配置类

这一步主要是通过框架自动生成Util工具类,交给Bean管理,在这里为工具类传入所需要的QnOssProperties 参数信息

package com.sky.config;

import com.sky.properties.QnOssProperties;
import com.sky.utils.QnOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class OssConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public  QnOssUtil qnOssUtil(QnOssProperties qnOssProperties){
        log.info("文件上传配置类的参数:{}",qnOssProperties.getBucketName());
        log.info("七牛");
        return new QnOssUtil(qnOssProperties);
    }
}

配置对象QnOssProperties

这里通过@ConfigurationProperties(prefix = “sky.qnoss”)注解自动读取yaml文件,匹配sky.qnoss前缀对应的值给这些属性赋值。

package com.sky.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "sky.qnoss")
@Data
public class QnOssProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}

1. 添加七牛云OSS依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.2.0, 7.999.999]</version> </dependency> ``` 2. 配置七牛云OSS 在application.properties文件中添加以下配置: ``` # 七牛云OSS配置 qiniu.accessKey=your_access_key qiniu.secretKey=your_secret_key qiniu.bucket=your_bucket_name qiniu.pathPrefix=http://your_domain_name/ qiniu.zone=auto ``` 其中,`accessKey`和`secretKey`是七牛云账号的Access Key和Secret Key,`bucket`为存储空间名称,`pathPrefix`为访问域名前缀,`zone`为存储区域,这里设置为自动选择。 3. 创建七牛云OSS服务类 创建一个名为`QiniuOSSService`的类,用于封装七牛云OSS的操作方法。 ``` @Service public class QiniuOSSService { @Value("${qiniu.accessKey}") private String accessKey; @Value("${qiniu.secretKey}") private String secretKey; @Value("${qiniu.bucket}") private String bucket; @Value("${qiniu.pathPrefix}") private String pathPrefix; private Configuration configuration = new Configuration(Zone.autoZone()); private UploadManager uploadManager = new UploadManager(configuration); /** * 上传文件 * * @param file 文件 * @return 文件URL * @throws QiniuException 七牛云异常 */ public String uploadFile(File file) throws QiniuException { Auth auth = Auth.create(accessKey, secretKey); String token = auth.uploadToken(bucket); Response response = uploadManager.put(file, null, token); DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); return pathPrefix + putRet.key; } /** * 删除文件 * * @param key 文件key * @throws QiniuException 七牛云异常 */ public void deleteFile(String key) throws QiniuException { Auth auth = Auth.create(accessKey, secretKey); BucketManager bucketManager = new BucketManager(auth, configuration); bucketManager.delete(bucket, key); } } ``` 其中,`uploadFile`方法用于上传文件到七牛云OSS并返回文件URL,`deleteFile`方法用于删除文件。 4. 使用七牛云OSS服务类 在需要上传或删除文件的地方,注入`QiniuOSSService`并调用相应的方法即可。例如: ``` @RestController public class FileController { @Autowired private QiniuOSSService qiniuOSSService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException, QiniuException { File tempFile = File.createTempFile("temp", null); file.transferTo(tempFile); String fileUrl = qiniuOSSService.uploadFile(tempFile); tempFile.delete(); return fileUrl; } @DeleteMapping("/delete") public void deleteFile(@RequestParam("key") String key) throws QiniuException { qiniuOSSService.deleteFile(key); } } ``` 这里提供了一个上传和删除文件的示例接口,上传的文件可以是`MultipartFile`类型,需要先将其转换为`File`类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值