SpringBoot 整合七牛云做上传图片

第一步 ~ 环境准备

注册七牛云-> 登录成功后点击控制台——左边找到->对象存储Kodo 没有空间的话 新建一个华东的

-> 点击空间管理——> 新建空间新建好了点进空间里面 空间概览右边有 CDN测试域名这个只有30天!!

点击文件管理——>新建一个目录为 code点进code 目录 在新建duck 就好了 code/duck 最后就是我们

程序里面需要用到 这个目录可以随便建的! 在点击图片样式! 按照你自己的要求弄一个就好!

密钥!在哪呢!!!! 如下

我们实现这个还需要一个 key 和 密钥 在哪里查看呢

点击我们登录的头像! 点击密钥管理 第一个 AK SK 就是了

第二部 ~ 接下来就是编写代码环节

导入依赖!!

       <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.25</version>
        </dependency>

把七牛云域名等那些在yaml 中配置

package com.qiniuoss.config;

import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Slf4j(topic = "七牛云配置")
@SuppressWarnings("all")
@ConfigurationProperties(prefix = "qiniuoos")
@Component
@ConstructorBinding
@ConfigurationPropertiesScan(basePackages = "package com.qiniuoss.config.CloudStorageConfigs")
@ToString
public class CloudStorageConfigs {
    /**
     * <per>
     *     1 [ 七牛域名domain ]   2  [ 七牛ACCESS_KEY ]  3 [ 七牛SECRET_KEY  ]   4 [ 七牛空间名 ]
     * </per>
     */
    private String  SEVENNIUYUNDOMAINNAME;
    private String  ACCESS_KEY;
    private String  SECRET_KEY;
    private String  SEVENCATTLENAMESPACE;
}

对呀yaml

qiniuoos:
  SEVENNIUYUNDOMAINNAME: CDN 测试域名 或者你自己配置好的域名
  ACCESS_KEY: 你的AK
  SECRET_KEY: 你的SK
  SEVENCATTLENAMESPACE: 七牛云空间名

我们新建一个抽象类用于我们调用

package com.qiniuoss.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
@Component
public abstract class UploadImageService {

        @Autowired
        protected  CloudStorageConfigs cloudStorageConfig; //上面 文件
        public abstract String uploadQNImg(InputStream file, String path);
}

有抽象类 肯定少不了实现类啊 那就我们来新建一个

package com.qiniuoss.config;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;

import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
@Slf4j(topic = "七牛云")
@SuppressWarnings("all")
public class UploadImageServiceImpl extends  UploadImageService{

    private UploadManager uploadManager;

    private String token;
    // 七牛认证管理
    private Auth auth;

    public UploadImageServiceImpl(CloudStorageConfigs config) {
        this.cloudStorageConfig = config;
        init();
    }
    private void init() {
        // 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
        Configuration cf = new Configuration(Zone.zone0());
        uploadManager = new UploadManager(cf);
        auth = Auth.create(cloudStorageConfig.getACCESS_KEY(),cloudStorageConfig.getSECRET_KEY());
        // 根据命名空间生成的上传token
        token = auth.uploadToken(cloudStorageConfig.getSEVENCATTLENAMESPACE());
        log.info("token->>::{}",token);
    }

    @Override
    public String uploadQNImg(InputStream file, String key) {
        try {
            // 上传图片文件
            Response res = uploadManager.put(file, key, token, null, null);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错:" + res.toString());
            }
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);

            String paths = cloudStorageConfig.getSEVENNIUYUNDOMAINNAME() + "/" + putRet.key;
            // 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
            return paths;
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return "";
    }
}

还有一个上传文件工具类:

package com.qiniuoss.config;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@SuppressWarnings("all")
@Component
@RequiredArgsConstructor
public class FileEqualsUtil {
    private final  UploadImageService uploadImageService;

    @Value("${web.upload_dir}")  //等下我们需要到yml 中配置
    private String uploadPath;
    /**
     * 判断文件是否存在,并上传到服务器返回访问路径
     * @param file
     * @return
     */
    @SneakyThrows
    public String fileEquals(MultipartFile file){
        if(!file.isEmpty()){
            String fileName=file.getOriginalFilename();
            InputStream inputStream=file.getInputStream();
            String path=uploadImageService.uploadQNImg(inputStream,fileName);
            return path;
        }
        return null;
    }

    /**
     * 判断文件是否存在,并上传到本地返回访问路径
     * @param request
     * @param file
     * @return
     */
    @SneakyThrows
    public HashMap<String,String> fileBenSave(HttpServletRequest request, MultipartFile file){
        HashMap<String,String> map=new HashMap<>();
        String fileName=file.getOriginalFilename();
        byte[] bytes=file.getBytes();
        String certificateKey=new String(bytes);
        String pathName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        File upload=new File(uploadPath);
        if(!upload.isDirectory()){
            upload.mkdirs();
        }
        // 文件保存
        file.transferTo(new File(upload,pathName));
        String path=upload+"\\"+pathName;
        map.put("certificateKey",certificateKey);
        map.put("path",path);
        return map;
    }
}

防止图片名字重名:

package com.qiniuoss.config;

import cn.hutool.core.date.DateUtil;

import java.util.UUID;
@SuppressWarnings("all")
public class StringUtil {
    /**
     * @Description: 生成唯一图片名称
     * @Param: fileName
     * @return: 云服务器fileName
     */
    public static String getRandomImgName(String fileName) {

        int index = fileName.lastIndexOf(".");

        if ((fileName == null || fileName.isEmpty()) || index == -1){
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index);
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 生成上传至云服务器的路径
        String path = "code/duck/" + DateUtil.today() + "-" + uuid + suffix;  //code/duck/ 就是你七牛云上面新建的
        return path;
    }
}

我们刚刚说了还需要在 yml 中配置

spring:
  web:
    resources:
      static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload_dir}
web:
  #upload_dir: /usr/liwei-iot_tool/tomcat_tool/apache-tomcat-9.0.55/webapps/ROOT/WEB-   INF/classes/upload/  # 上传文件到服务器的路径
  upload_dir: D:/upload/  # 上传文件到本地的路径

接下来就是接口编写 访问就行了

String path = "";
    @SneakyThrows
    @RequestMapping(value = "/upda",method = RequestMethod.POST)
    public Object isupda(@RequestParam("upfile") MultipartFile upfile){
        String fileName = upfile.getOriginalFilename();
        String voicefileName = StringUtil.getRandomImgName(fileName);
        Optional.ofNullable(upfile).ifPresent(j->{
            InputStream inputStream = null;
            try {
                inputStream = upfile.getInputStream();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            path = uploadImageService.uploadQNImg(inputStream, voicefileName);
        });
        log.info("()——>[图片地址为]::{}:",path);
        return ResultResponse.SUCCESS(path);
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

杰哥力挽狂澜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值