使用gitlab作为图床


保存图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@ResponseBody
@RequestMapping(value = "/img-upload", method = RequestMethod.POST)
private Map<String, Object> imgUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request)
throws Exception {

// 获得物理路径webapp所在路径
String pathRoot = request.getSession().getServletContext().getRealPath("");
pathRoot = request.getSession().getServletContext().getRealPath("resources/upload/images/");

File fileDir = new File(pathRoot);
if (!fileDir.exists()) {
// 递归生成文件夹
fileDir.mkdirs();
}
String path = "";
List<String> imgs = new ArrayList<>();
if (files != null && files.length > 0) {

for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];

// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件类型(可以判断如果不是图片,禁止上传)
String contentType = file.getContentType();
// 获得文件后缀名称
String imageName = contentType.substring(contentType.indexOf("/") + 1);
path = uuid + "." + imageName;

// 上传到gitlab
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("PRIVATE-TOKEN", "tvimWu7W6QhmuwHZ8cTe");
JSONObject body = new JSONObject();
body.put("branch", "master");
body.put("author_email", "gech@yoozoo.com");
body.put("author_name", "gech");
body.put("encoding", "base64");
body.put("content", Encodes.encodeBase64(file.getBytes()));
body.put("commit_message", "upload image");

HttpEntity<String> request1 = new HttpEntity<String>(body.toString(), headers);

String responseString = restTemplate.postForObject(
"https://gitlab.uuzu.com/api/v4/projects/1766/repository/files/" + path, request1,
String.class);

imgs.add("https://gitlab.uuzu.com/datacenter/images/raw/master/" + path);
}

}

Map<String, Object> result = new HashMap<>();
result.put("errno", 0);
result.put("data", imgs);

return result;
}

  github
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×