SpringBoot项目集成七牛云(能简单使用上传功能)

从网上也看了很多文章, 但是想想还是自己写一个吧, 主要是问题太多了!!

也是因为以前有用过一点, 没事可以去上面玩玩, 存些只能自己看的东东拉(坏笑!)

最近要用到文件上传功能(云存储), 想想还是拿起了之前用过的七牛云, 话不多说直接上图

 大致结构就是这样, 这样只是标准点springboot项目的样子, 各位怎么习惯怎么来

类名, 接口名, html页面名, 大家随意, 不用一样, 调用的时候注意点就行..

先说说最重要的yml文件把

 可能大家的yml文件也不是yml结尾的, 也有properties结尾的,也有yaml结尾的, 这个没去测

一定一定一定要注意的地方, 格式!!! 

看看空格什么的, 不然肯定报错, 冒号( : ) 后面有空格!!!

下面就是url具体的地址了, 这里就不方便看了, 大致就是这里, (https://portal.qiniu.com/cdn/domain)

 然后就是下面了, 在个人中心里面(别找不到0.0), 就对应的 AK, SK, 这不会输错吧(https://portal.qiniu.com/user/key)

 然后就是空间名称了, (https://portal.qiniu.com/kodo/bucket)

 先自己新建一个, 还有注意存储区域, 后面代码要有用到...到这, yml文件就没了

下面是具体代码部分

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @Date: 2021/08/17/10:32
 * @Description:
 */
@Data
@Configuration
public class QiNiuYunConfig {

    /**
     * 七牛域名domain
     */
    @Value("${oss.qiniu.url}")
    private String url;

    /**
     * 七牛ACCESS_KEY
     */
    @Value("${oss.qiniu.accessKey}")
    private String AccessKey;

    /**
     * 七牛SECRET_KEY
     */
    @Value("${oss.qiniu.secretKey}")
    private String SecretKey;

    /**
     * 七牛空间名
     */
    @Value("${oss.qiniu.bucketName}")
    private String BucketName;

}
package com.xhl.controller;

import com.xhl.service.UploadImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @Date: 2021/08/17/10:34
 * @Description:
 */
@Slf4j
@Controller
@RequestMapping("/qiniu")
public class UploadController {

    @Autowired
    private UploadImageService uploadImageService;

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @GetMapping("/display")
    public String display() {
        return "upload";
    }

    @GetMapping("/qiniu1")
    public String qiniu1(){
        System.out.println("qiniu111111112222");
        return  "QiNiuYunTest.html";
    }

    @RequestMapping(value = "/image",method = RequestMethod.POST)
    private String upLoadImage(@RequestParam("file") MultipartFile file, Model model) {
        if (!file.isEmpty()) {
            String path2 = "";
            String path = uploadImageService.uploadQNImg(file);
            path2 = "http://" + path;
            System.out.print("七牛云返回的图片链接: " + path2);
            model.addAttribute("link", path2);
            return "QiNiuYunTest.html";
    }

    /*
     * 这里为了方便测试才这么写的 可以根据实际需要 自己写。
     * @Param
     * @return java.lang.String
     **/
    @ResponseBody
    @RequestMapping(value = "/remove",method = RequestMethod.DELETE)
    public String removeFile() {
        uploadImageService.removeFile("xj-xueyi", "微信图片_20210721145425.png");
        return "删除成功";
    }

}
package com.xhl.service;

import org.springframework.web.multipart.MultipartFile;

/**
 * @Date: 2021/08/17/10:48
 * @Description:
 */
public interface UploadImageService {
    String uploadQNImg(MultipartFile file);

    String getPrivateFile(String fileKey);

    boolean removeFile(String bucketName, String fileKey);

}
package com.xhl.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.xhl.utils.StringUtil;
import com.xhl.config.QiNiuYunConfig;
import com.xhl.service.UploadImageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author hl
 * @Date: 2021/08/17/10:48
 * @Description:
 */
@Service
public class UploadImageServiceImpl implements UploadImageService {
    private QiNiuYunConfig qiNiuYunConfig;

    // 七牛文件上传管理器
    private UploadManager uploadManager;
    //上传的token
    private String token;
    // 七牛认证管理
    private Auth auth;

    private BucketManager bucketManager;

    public UploadImageServiceImpl(QiNiuYunConfig qiNiuYunConfig) {
        this.qiNiuYunConfig = qiNiuYunConfig;
        init();
    }

    private void init() {
        // 构造一个带指定Zone对象的配置类, 注意这里的Zone.zone0需要根据主机选择
        uploadManager = new UploadManager(new Configuration(Zone.zone0()));
        auth = Auth.create(qiNiuYunConfig.getAccessKey(), qiNiuYunConfig.getSecretKey());
        // 根据命名空间生成的上传token
        bucketManager = new BucketManager(auth, new Configuration(Zone.zone0()));
        token = auth.uploadToken(qiNiuYunConfig.getBucketName());
    }

    /*
     * 上传文件
     * @Param [file, key]
     * @return java.lang.String
     **/
    @Override
    public String uploadQNImg(MultipartFile file) {
        try {
            // 获取文件的名称
            String fileName = file.getOriginalFilename();

            // 使用工具类根据上传文件生成唯一图片名称
            String imgName = StringUtil.getRandomImgName(fileName);

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

            // 直接返回外链地址
            return getPrivateFile(imgName);
        } catch (QiniuException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取私有空间文件
     *
     * @param fileKey
     * @return
     */
    @Override
    public String getPrivateFile(String fileKey) {
        String encodedFileName = null;
        String finalUrl = null;
        try {
            encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
            String publicUrl = String.format("%s/%s", this.qiNiuYunConfig.getUrl(), encodedFileName);
            long expireInSeconds = 3600;//1小时,可以自定义链接过期时间
            finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return finalUrl;
    }

    /*
     * 根据空间名、文件名删除文件
     * @Param [bucketName, fileKey]
     * @return boolean
     **/
    @Override
    public boolean removeFile(String bucketName, String fileKey) {
        try {
            bucketManager.delete(bucketName, fileKey);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return true;
    }

}
package com.xhl.utils;

import java.util.UUID;

/**
 * @Author hl
 * @Date: 2021/08/17/10:47
 * @Description:
 */
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 = "news/crush/"+ DateUtil.today() + "-" + uuid + suffix;
        String path = uuid + suffix;
        return path;
    }

}
package com.xhl;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

/**
 * @Author hl
 * @Date: 2021/08/17/10:13
 * @Description:
 */
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@MapperScan("com.xhl.config")
public class QiNiuYunApplication {
    public static void main(String[] args) {
        SpringApplication.run(QiNiuYunApplication.class,args);
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
<form action="/qiniu/image" method="post" enctype="multipart/form-data">
    <label>上传图片</label>
    <input type="file" name="file"/>
    <input type="submit" value="上传"/>
    <p>回显图片:</p>
    <img th:src="#{link}"/>
</form>
</body>
</html>

先看看编译有没有报错, 然后启动启动类, 如果没问题访问, localhost:端口/qiniu/qiniu1, 端口看你配置文件写的是啥, 

 大致页面是这样(抄的页面, 功能在就行), 选择文件 -> 上传, 看看有没有上传到七牛云

ok!!!大致就是这样了, 对了, 回显有问题, 大佬们不会介意把

可能在运行时报各种各样的错, 就当练习解决bug能力了

就先这样吧, 还有什么问题, 提出来一起讨论.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值