上传图片到gitee上面
项目背景
在平时的开发过程中,需要上传图片到服务器上面,但是服务器的容量是有限的,那么有没有免费的的? 当然是有啦,duang! 她来了!
项目搭建(工具idea)
1.新建项目
file->new->Project->maven->勾选 Create from archetype->quickstart 然后继续即可
按照顺序,依次执行
2.引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
<!-- 使用该库中的HttpUtil工具类来向Gitee发送请求 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
3.新建resources目录(若有,请忽略)
创建application.yml
文件
application.yml
文件如下
server:
port: 8080
# max-file-size:servlet每次接收单个文件的最大容量;max-request-size:指的是单次请求接收的文件最大容量
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 100MB
4.新建下面的几个工具类
DateUtil.java
package com.wlc.util;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* @author 王立朝
* @date 2022/3/17
* @description:
*/
public class DateUtil {
/**
* 返回当前的年月字符串,示例:2021-08
*
* @return 年月字符串
*/
public static String getDateTimeFormat(String format) {
return DateTimeFormatter.ofPattern(format).format(LocalDateTime.now());
}
}
FileUtils.java
package com.wlc.util;
/**
* @author 王立朝
* @date 2022/3/17
* @description:
*/
public class FileUtils {
/**
* 获取文件名的后缀,如:changlu.jpg => .jpg
* @return 文件后缀名
*/
public static String getFileSuffix(String fileName) {
return fileName.contains(".") ? fileName.substring(fileName.indexOf('.')) : null;
}
}
JsonResultUtil.java
统一返回类
package com.wlc.util;
/**
* @author 王立朝
* @description 统一返回类
* @date 2021-12-21 21:56:22
*/
public class JsonResultUtil<T> {
private Integer code;
private String msg;
private Object data;
public JsonResultUtil(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public JsonResultUtil() {
}
public JsonResultUtil<T> success(Object data) {
JsonResultUtil jsonResult = new JsonResultUtil<T>();
jsonResult.setCode(200);
jsonResult.setMsg("成功了!");
jsonResult.setData(data);
return jsonResult;
}
public JsonResultUtil<T> success() {
JsonResultUtil jsonResult = new JsonResultUtil<T>();
jsonResult.setCode(200);
jsonResult.setMsg("成功了!");
return jsonResult;
}
public JsonResultUtil<T> error(Integer code, String msg, Object obj) {
return new JsonResultUtil<T>(code, msg, obj);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
UploadGiteeImgBedUtil.java
上传图床工具类
package com.wlc.util;
import cn.hutool.core.codec.Base64;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author 王立朝
* @date 2022/3/17
* @description: 上传到gitee图床工具类
*/
public class UploadGiteeImgBedUtil {
/**
* 码云私人令牌
* c05e512c5def4b81e34060d1ed59f234
*/
public static final String ACCESS_TOKEN = "c05e512c5def4b81e34060d1ed59f234";
/**
* 码云个人空间名
*/
public static final String OWNER = "wanglichaohahaha";
/**
* 上传指定仓库
*/
public static final String REPO = "gitee-image-bed";
/**
* 上传时指定存放图片路径
* 使用到了日期工具类
*/
public static final String PATH = "/uploadImg/"+ DateUtil.getDateTimeFormat("yyyy-MM")+"/";
/**
* 用于提交描述
*/
public static final String ADD_MESSAGE = "add img";
public static final String DEL_MESSAGE = "DEL img";
//API
/**
* 新建(POST)、获取(GET)、删除(DELETE)文件:()中指的是使用对应的请求方式
* %s =>仓库所属空间地址(企业、组织或个人的地址path) (owner)
* %s => 仓库路径(repo)
* %s => 文件的路径(path)
*/
public static final String API_CREATE_POST = "https://gitee.com/api/v5/repos/%s/%s/contents/%s";
/**
* 生成创建(获取、删除)的指定文件路径
* @param originalFilename
* @return
*/
public static String createUploadFileUrl(String originalFilename){
//获取文件后缀
//使用到了自己编写的FileUtils工具类
String suffix = FileUtils.getFileSuffix(originalFilename);
//拼接存储的图片名称
String fileName = System.currentTimeMillis()+"_"+ UUID.randomUUID().toString()+suffix;
//填充请求路径
DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
String url = String.format(UploadGiteeImgBedUtil.API_CREATE_POST,
UploadGiteeImgBedUtil.OWNER,
UploadGiteeImgBedUtil.REPO,
UploadGiteeImgBedUtil.PATH+fileName);
return url;
}
/**
* 获取创建文件的请求体map集合:access_token、message、content
* @param multipartFile 文件字节数组
* @return 封装成map的请求体集合
*/
public static Map<String,Object> getUploadBodyMap(byte[] multipartFile){
HashMap<String, Object> bodyMap = new HashMap<>(3);
bodyMap.put("access_token",UploadGiteeImgBedUtil.ACCESS_TOKEN);
bodyMap.put("message", UploadGiteeImgBedUtil.ADD_MESSAGE);
bodyMap.put("content", Base64.encode(multipartFile));
return bodyMap;
}
}
5.修改启动类App.java
package com.wlc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
* @author wanglichao
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
6.新建控制器UploadController.java
package com.wlc.controller;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wlc.util.JsonResultUtil;
import com.wlc.util.UploadGiteeImgBedUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;
/**
* @author 王立朝
* @date 2022/3/17
* @description:
*/
@RestController
@Slf4j
public class UploadController {
/**
* 上传图片
*
* @param multipartFile 文件对象
* @return
* @throws IOException
*/
@PostMapping("/uploadImg")
public JsonResultUtil uploadImg(@RequestParam("file") MultipartFile multipartFile) throws IOException {
log.info("uploadImg()请求已来临...");
//根据文件名生成指定的请求url
String originalFilename = multipartFile.getOriginalFilename();
if (originalFilename == null) {
throw new RuntimeException("上传的文件为空!");
}
String targetURL = UploadGiteeImgBedUtil.createUploadFileUrl(originalFilename);
log.info("目标url:" + targetURL);
//请求体封装
Map<String, Object> uploadBodyMap = UploadGiteeImgBedUtil.getUploadBodyMap(multipartFile.getBytes());
//借助HttpUtil工具类发送POST请求
String JSONResult = HttpUtil.post(targetURL, uploadBodyMap);
//解析响应JSON字符串
JSONObject jsonObj = JSONUtil.parseObj(JSONResult);
//请求失败
if (jsonObj == null || jsonObj.getObj("commit") == null) {
new JsonResultUtil().error(200, "请求失败", null);
}
//请求成功:返回下载地址
JSONObject content = JSONUtil.parseObj(jsonObj.getObj("content"));
log.info("响应data为:" + content.getObj("download_url"));
return new JsonResultUtil<>().success(content.getObj("download_url"));
}
}
7.测试
请求地址:
localhost:8080/uploadImg
{
"code": 200,
"msg": "成功了!",
"data": "https://gitee.com/wanglichaohahaha/gitee-image-bed/raw/master/uploadImg/2022-03/1647510802881_2d4fabc9-b526-4bd9-bd65-141acd6002af.jpg"
}
访问浏览器
阳光总在风雨后!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了