在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</