在SpringBoot中通过RestTemplate提交文件到Github(白嫖图床)

在SpringBoot中通过RestTemplate提交文件到Github(白嫖图床)

Github仓库 + jsDelivr = 全球加速的免费图床

之前写过一篇帖子,GitHub + jsDelivr CDN 全球加速的免费图床,它不香吗? 这篇帖子中,使用的是桌面客户端 PicGo,进行图片上传的。在这里我们使用SpringBoot中的RestTemplate作为客户端,上传文件到Github仓库。

先在Github中创建一个public的仓库,和AccessToken

参考上面的帖子,这里不再重复讲诉。

SpringBoot的yml文件中添加配置

github:
  bucket:
    # 配置仓库所属的用户名(如果是自己创建的,就是自己的用户名)
    user: "springboot-community"
    # 配置仓库名称
    repository: "twitter-bucket"
    # 配置自己的acccessToken
    access-token: "996e748cb47117adbf3**********"
    url: "https://cdn.jsdelivr.net/gh/${github.bucket.user}/${github.bucket.repository}/"
    api: "https://api.github.com/repos/${github.bucket.user}/${github.bucket.repository}/contents/"

你只需要配置好,上面自己有注释的3个配置就OK了

GithubUploaderGithubUploader

封装的一个工具类,根据上面的配置进行文件的上传

  • 使用UUID重新命名文件,防止冲突
  • 根据日期打散目录:yyyy/mm/dd
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;



@Component
public class GithubUploader {
   
	
	private static</
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值