项目地址:https://gitee.com/cwayteam/TyporaUpload
相关使用可参考项目中介绍哦!使用了 hutool,建议 jdk9+。
代码:
package top.cway;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.EscapeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {public static void main(String[] args) {for (String arg : args) {System.out.println(upload(arg));
}
}
public static String upload(String path) {// 新建 cookie.txt 放在 jar 包所在路径 并将路过图床 (https://imgchr.com/) 的 cookie 放进去
String path1 = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
path1 = path1.substring(0, path1.lastIndexOf("/")) + "/cookie.txt";
String cookie = new FileReader(path1).readString();
cookie = EscapeUtil.escape(cookie);
// 页面获取 auth_token
HttpResponse resp = HttpRequest.get("https://imgchr.com/1")
.header("Cookie", cookie)
.execute();
Pattern pattern = Pattern.compile("PF.obj.config.auth_token = \"(.*?)\";");
Matcher matcher = pattern.matcher(resp.body());
String token = "";
if (matcher.find()) {token = matcher.group(1);
}
// 根据路径上传文件并返回上传后的图片地址
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("source", FileUtil.file(path));
paramMap.put("type", "file");
paramMap.put("action", "upload");
paramMap.put("timestamp", System.currentTimeMillis());
paramMap.put("auth_token", token);
paramMap.put("nsfw", "0");
HttpResponse result = HttpRequest.post("https://imgchr.com/json")
.header("Cookie", cookie)
.form(paramMap).execute();
return JSONUtil.parse(result.body()).getByPath("image.url").toString();}
}