ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot整合七牛云上传图片

2021-05-17 15:01:33  阅读:181  来源: 互联网

标签:七牛云 String com qiniu springframework import org 上传 SpringBoot


准备工作

1.注册并实名认证七牛云账号
不进行实名认证将不能创建空间,审核最多需要三个工作日,但通常实名认证过后1~2个小时就能收到认证成功的信息。
2.创建空间
在这里插入图片描述
3.获取几个重要信息

  • AK 和 SK

在这里插入图片描述

  • 空间名称

也就是创建空间时自己去的名字

  • 临时域名

在这里插入图片描述

代码

yml配置

oss:
  qiniu:
    domain: qtxxxxxxxx.hn-xxx.xxxxx.com # 访问域名(默认使用七牛云测试域名)
    accessKey: Gn0uwxxxxxxxxxxxxxxxxxxxxy3GEVmZqR58ed # 公钥 刚才的AK
    secretKey: hs-ScVOxxxxxxxxxxxo0yG33uHm8_NkmnKy # 私钥 刚才的SK
    bucketName: officxxxxxxxxxxicture  #存储空间名称

配置类

package studio.banner.officialwebsite.config;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author: Re
 * @Date: 2021/5/15 20:48
 */
@Data
@Component
public class QiNiuYunConfig {
    /**
     * 七牛域名domain
     */
    @Value("${oss.qiniu.domain}")
    private String qiniuDomain;
    /**
     * 七牛ACCESS_KEY
     */
    @Value("${oss.qiniu.accessKey}")
    private String qiniuAccessKey;
    /**
     * 七牛SECRET_KEY
     */
    @Value("${oss.qiniu.secretKey}")
    private String qiniuSecretKey;
    /**
     * 七牛空间名
     */
    @Value("${oss.qiniu.bucketName}")
    private String qiniuBucketName;
}

Service接口

package studio.banner.officialwebsite.service;

import java.io.FileInputStream;

/**
 * @Author: Re
 * @Date: 2021/5/15 22:42
 */
public interface IQiNiuYunService {
    /**
     * 上传照片
     * @return
     * @param file
     * @param path
     */
    String updatePhoto(String path, FileInputStream file);
}

Service实现

package studio.banner.officialwebsite.service.Impl;

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import studio.banner.officialwebsite.config.QiNiuYunConfig;
import studio.banner.officialwebsite.service.IQiNiuYunService;

import java.io.FileInputStream;

/**
 * @Author: Re
 * @Date: 2021/5/15 22:43
 */
@Service
public class QiNiuYunServiceImpl implements IQiNiuYunService {
    protected static Logger logger = LoggerFactory.getLogger(QiNiuYunServiceImpl.class);
    @Autowired
    QiNiuYunConfig qiNiuYunConfig;
    @Override
    public String updatePhoto(String key, FileInputStream file) {
        /**
         * 构造一个带指定Region对象的配置类
         */
        Configuration cfg = new Configuration(Region.region2());
        /**
         * 其他参数参考类注释
         */
        UploadManager uploadManager = new UploadManager(cfg);
        /**
         * 生成上传凭证,然后准备上传
         */
        logger.info("密钥信息"+qiNiuYunConfig.getQiniuBucketName()+qiNiuYunConfig.getQiniuAccessKey()+qiNiuYunConfig.getQiniuSecretKey());
        Auth auth = Auth.create(qiNiuYunConfig.getQiniuAccessKey(), qiNiuYunConfig.getQiniuSecretKey());
        String upToken = auth.uploadToken(qiNiuYunConfig.getQiniuBucketName());
        try {
            Response response = uploadManager.put(file, key, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            logger.info(putRet.key);
            logger.info(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.error(r.toString());
            try {
                logger.error(r.bodyString());
            } catch (QiniuException e) {
                r = e.response;
                logger.error(r.toString());
            }
        }
        return "http://"+qiNiuYunConfig.getQiniuDomain()+"/"+key;
    }
}

Controller层

package studio.banner.officialwebsite.controller.background;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import studio.banner.officialwebsite.service.IQiNiuYunService;

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

/**
 * @Author: Re
 * @Date: 2021/5/16 7:55
 */
@RestController
@Api(tags = "上传图片接口",value = "UploadPhotoController")
public class UploadPhotoController {
    @Autowired
    protected IQiNiuYunService qiNiuYunService;
    @PostMapping("/upload")
    @ApiOperation(value = "上传图片",notes = "上传图片不能为空",httpMethod = "POST")
    public String upload(@RequestPart MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 生成随机的图片名
        String imgName = UUID.randomUUID() + "-" +fileName;
        if (!file.isEmpty()) {

            FileInputStream inputStream = null;
            try {
                inputStream = (FileInputStream) file.getInputStream();
                String path = qiNiuYunService.updatePhoto(imgName,inputStream);
                System.out.print("七牛云返回的图片链接:" + path);
                return path;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "上传失败";
        }
        return "上传失败";
    }
}

Swagger测试

在这里插入图片描述
响应体为
在这里插入图片描述
复制链接进入
在这里插入图片描述
文章参考:
https://www.cnblogs.com/code-duck/p/13406348.html
七牛云JAVASDK

标签:七牛云,String,com,qiniu,springframework,import,org,上传,SpringBoot
来源: https://blog.csdn.net/weixin_52025712/article/details/116932311

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有