SpringBoot(24) 整合七牛云实现文件上传

一、前言

本文将基于springboot2.1.8.RELEASE整合七牛云实现文件上传

本文参考 https://www.keppel.fun/articles/2019/02/27/1551262881214.html

二、准备(AccessKeySecretKey对象储存空间名称存储区域访问域名)

1、先到七牛云官网获取AccessKey/SecretKey

温馨小提示:没有账号的可以先注册一个使用~

在这里插入图片描述

2、在对象储存中创建一个空间,然后拿到存储空间名称存储区域访问域名

温馨小提示:这里只是为了体验七牛云的文件上传功能,在访问控制处可暂时选择公开,后面是可以修改权限的,不用担心~

在这里插入图片描述
新建成功之后,七牛云给了一个测试域名可供使用一个月
在这里插入图片描述

三、SpringBoot集成七牛云

1、pom.xml中引入依赖
<!-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -->
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.2.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>
2、application.yml中配置七牛云
# ========================== ↓↓↓↓↓↓ 七牛云配置 ↓↓↓↓↓↓ ==========================
qiniu:
  accessKey: xxx
  secretKey: xxx
  # 对象储存
  bucket: zhengqingya # 空间名称
  zone: huadong # 存储区域
  domain: q6nf5vyrf.bkt.clouddn.com # 访问域名
3、七牛云配置类
@Configuration
public class QiniuConfig {

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

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.zone}")
    private String zone;

    /**
     * 配置空间的存储区域
     */
    @Bean
    public com.qiniu.storage.Configuration qiNiuConfig() {
        switch (zone) {
            case "huadong":
                return new com.qiniu.storage.Configuration(Zone.huadong());
            case "huabei":
                return new com.qiniu.storage.Configuration(Zone.huabei());
            case "huanan":
                return new com.qiniu.storage.Configuration(Zone.huanan());
            case "beimei":
                return new com.qiniu.storage.Configuration(Zone.beimei());
            default:
                throw new MyException("存储区域配置错误");
        }
    }

    /**
     * 构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager() {
        return new UploadManager(qiNiuConfig());
    }

    /**
     * 认证信息实例
     */
    @Bean
    public Auth auth() {
        return Auth.create(accessKey, secretKey);
    }

    /**
     * 构建七牛空间管理实例
     */
    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth(), qiNiuConfig());
    }

    @Bean
    public Gson gson() {
        return new Gson();
    }

}
4、编写文件上传与删除方法

服务类:

public interface IQiniuService {

    /**
     * 以文件的形式上传
     *
     * @param file
     * @param fileName:
     * @return: java.lang.String
     */
    String uploadFile(File file, String fileName) throws QiniuException;

    /**
     * 以流的形式上传
     *
     * @param inputStream
     * @param fileName:
     * @return: java.lang.String
     */
    String uploadFile(InputStream inputStream, String fileName) throws QiniuException;

    /**
     * 删除文件
     *
     * @param key:
     * @return: java.lang.String
     */
    String delete(String key) throws QiniuException;

}

服务实现类:

@Service
public class QiniuServiceImpl implements IQiniuService, InitializingBean {

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    /**
     * 定义七牛云上传的相关策略
     */
    private StringMap putPolicy;

    @Override
    public String uploadFile(File file, String fileName) throws QiniuException {
        Response response = this.uploadManager.put(file, fileName, getUploadToken());
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(file, fileName, getUploadToken());
            retry++;
        }
        if (response.statusCode == 200) {
            return "http://" + domain + "/" + fileName;
        }
        return "上传失败!";
    }

    @Override
    public String uploadFile(InputStream inputStream, String fileName) throws QiniuException {
        Response response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
        int retry = 0;
        while (response.needRetry() && retry < 3) {
            response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
            retry++;
        }
        if (response.statusCode == 200) {
            return "http://" + domain + "/" + fileName;
        }
        return "上传失败!";
    }


    @Override
    public String delete(String key) throws QiniuException {
        Response response = bucketManager.delete(this.bucket, key);
        int retry = 0;
        while (response.needRetry() && retry++ < 3) {
            response = bucketManager.delete(bucket, key);
        }
        return response.statusCode == 200 ? "删除成功!" : "删除失败!";
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }

    /**
     * 获取上传凭证
     */
    private String getUploadToken() {
        return this.auth.uploadToken(bucket, null, 3600, putPolicy);
    }

}

四、测试文件上传与删除

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class QiniuTest {

    @Autowired
    private IQiniuService qiniuService;

    @Test
    public void testUpload() throws QiniuException {
        String result = qiniuService.uploadFile(new File("D:\\IT_zhengqing\\image\\helloworld.jpg"), "helloworld");
        System.out.println("访问地址: " + result);
    }

    @Test
    public void testDelete() throws QiniuException {
        String result = qiniuService.delete("helloworld");
        System.out.println(result);
    }

}

本文案例demo源码

https://gitee.com/zhengqingya/java-workspace

实现Spring Boot整合七牛云上传文件,可以按照以下步骤进行: 1.引入七牛云Java SDK 在pom.xml中引入七牛云Java SDK: ```xml <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.2.0,)</version> </dependency> ``` 2.配置七牛云参数 在application.yml或application.properties中添加七牛云的参数: ```yml qiniu: accessKey: your_access_key secretKey: your_secret_key bucket: your_bucket_name domain: your_domain_name ``` 3.编写上传文件的代码 在需要上传文件的地方编写上传文件的代码,示例代码如下: ```java @Service public class QiniuService { @Autowired private QiniuConfig qiniuConfig; /** * 上传文件七牛云 * * @param file 文件对象 * @return 文件访问URL */ public String uploadFile(File file) throws QiniuException { // 构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.autoZone()); // ...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); // 生成上传凭证,然后准备上传 String accessKey = qiniuConfig.getAccessKey(); String secretKey = qiniuConfig.getSecretKey(); String bucket = qiniuConfig.getBucket(); // 如果是Windows情况下,格式是 D:\\qiniu\\test.png String localFilePath = file.getAbsolutePath(); // 默认不指定key的情况下,以文件内容的hash值作为文件名 String key = null; 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); return qiniuConfig.getDomain() + "/" + putRet.key; } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { // ignore } throw ex; } } } ``` 4.测试上传文件 在测试类中编写测试上传文件的代码,示例代码如下: ```java @RunWith(SpringRunner.class) @SpringBootTest public class QiniuServiceTest { @Autowired private QiniuService qiniuService; @Test public void testUploadFile() throws QiniuException { File file = new File("test.png"); String url = qiniuService.uploadFile(file); System.out.println(url); } } ``` 其中,test.png是要上传的文件名。运行测试类即可上传文件七牛云,并返回文件的访问URL。 以上就是Spring Boot整合七牛云上传文件的全部步骤。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值