Spring Boot 使用七牛云存储图片并且使用自定义域名访问

Spring Boot 使用七牛云存储图片并且使用自定义域名访问,第1张

文章目录
  • 前言
  • 一、环境准备
    • 1. 账号准备
      • 注册七牛云账号并实名
      • 创建对象存储空间
      • 获取密钥
    • 2. 创建spring boot 项目
      • pom.xml
      • application.yml
  • 二、上传本地文件测试
    • QiniuServiceImpl.java
    • 测试代码
  • 三、从浏览器上传文件
    • 修改后的 FileController.java
    • 修改后的QiniuServiceImpl.java
  • 四、源码地址


前言

七牛云为每个用户提供了10G免费存储空间。个人使用还是很香的。本文将记录如何上传文件。


一、环境准备 1. 账号准备 注册七牛云账号并实名

https://s.qiniu.com/b2qUry

创建对象存储空间

https://portal.qiniu.com/kodo/bucket

获取密钥

https://portal.qiniu.com/user/key


注意保管好自己的密钥

2. 创建spring boot 项目

pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>com.qiniugroupId>
            <artifactId>qiniu-java-sdkartifactId>

            <version>[7.7.0, 7.10.99]version>
        dependency>

        <dependency>
            <groupId>com.squareup.okhttp3groupId>
            <artifactId>okhttpartifactId>
            <version>3.14.2version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>com.qiniugroupId>
            <artifactId>happy-dns-javaartifactId>
            <version>0.1.6version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.71version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.1version>
            <scope>testscope>
        dependency>
    dependencies>

注意:从 7.2.24 开始,okhttp3 升级到 3.14.2,其要求 java 1.8 及以上。
若一定 java 1.7 ,请手动指定 okhttp3 依赖 3.12,要求 3.12.3 及以上

application.yml
logging:
  level:
    root: warn
    com.king: info
    org.springframework: error

Qiniu:
  AccessKey: xxxxxxxxxxx上述步骤获取密钥 你的AccessKey
  SecretKey: xxxxxxxxxx你的SecretKey xxxxxxxxxxxxxxxx
  
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

二、上传本地文件测试 QiniuServiceImpl.java

代码如下:

package com.king.oss.service;

import com.alibaba.fastjson.JSON;
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.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: 12613
 * @project: mooc
 * @pcakage: com.king.mooc.service.impl.QiniuServiceImpl
 * @date: 2022年05月02日 00:38
 * @description:
 */
@Service
public class QiniuServiceImpl {
    @Value(value = "${Qiniu.AccessKey}")
    private String accessKey;
    @Value(value = "${Qiniu.SecretKey}")
    private String secretKey;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //测试文件上传
    public void testUpload() {
        //构造一个带指定 Region 对象的配置类,指定存储区域,和存储空间选择的区域一致
        //
        Configuration cfg = new Configuration(Region.huanan());
        //其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证,然后准备上传
        String bucket = "hnking";
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = UUID.randomUUID() + ".png";
        FileInputStream fileInputStream = null;
        try {

            String filePath = "C:\Users\12613\Pictures\20201029195525.png";
            fileInputStream = new FileInputStream(new File(filePath));
            //得到本地文件的字节数组
            byte[] bytes = IOUtils.toByteArray(fileInputStream);
            //认证
            Auth auth = Auth.create(accessKey, secretKey);
            //认证通过后得到token(令牌)
            String upToken = auth.uploadToken(bucket);
            try {
                //上传文件,参数:字节数组,key,token令牌
                //key: 建议我们自已生成一个不重复的名称
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(),
                        DefaultPutRet.class);
                logger.info("上传成功{}", JSON.toJSONString(putRet));
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                   logger.error("上传失败{}",ex2.getMessage());
                }
            }
        } catch (IOException ex) {
            logger.error("上传文件失败", ex); 
        }

    }
}
测试代码

QiniuServiceImplTest.java

package com.king.oss.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class QiniuServiceImplTest {

    @Autowired
    private QiniuServiceImpl qiniuService;


    @Test
    public void uploadFile() {
        qiniuService.testUpload();
    }

}

运行结果

使用七牛云提供的测试域名
rb3lparfv.hn-bkt.clouddn.com/834c9118-ee9e-4d31-a247-5998d9ddbeed.png
即可访问图片


三、从浏览器上传文件

这里先参考之前的文章:SpringBoot 使用表单或者vue实现文件上传

修改后的 FileController.java
package com.king.oss.controller;

import com.king.oss.service.QiniuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @program: springboot
 * @description:
 * @author: King
 * @create: 2022-01-30 23:09
 */
@RestController
@RequestMapping("/file")
public class FileController {

    //默认上传到的路径

    @Autowired
    QiniuServiceImpl qiniuService;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req) {
        if (!uploadFile.isEmpty()) {
            return qiniuService.saveFile(uploadFile);
        }
        return "上传失败!";
    }

    @PostMapping("/uploads")
    public List<String> upload(@RequestParam("files") MultipartFile[] uploadFiles, HttpServletRequest req) {
        if (!ObjectUtils.isEmpty(uploadFiles) && uploadFiles.length > 0) {
            return qiniuService.saveFile(uploadFiles);
        }
        return Collections.singletonList("上传失败!");
    }


}

修改后的QiniuServiceImpl.java
package com.king.oss.service;

import com.alibaba.fastjson.JSON;
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.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: 12613
 * @project: mooc
 * @pcakage: com.king.mooc.service.impl.QiniuServiceImpl
 * @date: 2022年05月02日 00:38
 * @description:
 */
@Service
public class QiniuServiceImpl {
    @Value(value = "${Qiniu.AccessKey}")
    private String accessKey;
    @Value(value = "${Qiniu.SecretKey}")
    private String secretKey;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    public String saveFile(MultipartFile uploadFile) {
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String bucket = "hnking";
        String fileName = uploadFile.getOriginalFilename();
        String key = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(uploadFile.getBytes(), key, upToken);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return "http://rb3lparfv.hn-bkt.clouddn.com/" + putRet.key;
        } catch (QiniuException e) {
            logger.error("上传文件失败", e);
            logger.error(JSON.toJSONString(e.response));
        } catch (IOException e) {
            logger.error("上传文件失败", e);
        }
        return null;
    }

    public List<String> saveFile(MultipartFile[] uploadFiles) {
        List<String> list = new ArrayList<>();
        for (MultipartFile uploadFile : uploadFiles) {
            list.add(saveFile(uploadFile));
        }
        return list;
    }
}


http://rb3lparfv.hn-bkt.clouddn.com/ff63da0f-bbe2-4f96-9edd-531ec98ffdd1.png

ok 完美运行


四、源码地址

Github https://github.com/KingJin-web/springboot

Gitee https://gitee.com//KingJin-web/springboot

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/794605.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-06
下一篇 2022-05-06

发表评论

登录后才能评论

评论列表(0条)

保存