利于GitHub制作在线图床

安辰
2023-07-20 0 评论 45 阅读 正在检测是否收录...
温馨提示:
本文最后更新于2023年07月20日,已超过282天没有更新,若内容或图片失效,请留言反馈。

众所周知,github的api灰常开放,如今已经有picog+github图床,但是,picog是桌面程序,怎样能用用一个网页程序来实现呢?其实很简单,我们就单纯用一个ajax请求就可以了
以下是一段简单的上传函数

 function uploadimg(file, form) {
            // alert(4)
            let timestamp = new Date().getTime(); //获取时间戳
            let newname = "https://raw.githubusercontent.com/你的用户名/仓库名/目录(留空代表根目录)/" + timestamp + "." + form; //以事件戳重命名
            console.log(newname);
            $.ajax({
                url: "https://api.github.com/repos/你的用户名/仓库名/目录(留空代表根目录)/" + timestamp + "." + form,
                method: "PUT",
                headers: {
                    "Authorization": "密钥,在github的个人 左侧的申请",
                    "Content-Type": "text/plain"
                },
                data: "{\r\n "message": "upload",\r\n "content": "" + file + ""\r\n}",
                success: function () {
                    console.log(111);
                    $("#neirong").html("github:" + newname) //写到html里面
                }
            })
        }

当然,图片上传时我们还要对图片进行重命名,避免重复图片,同时还要对图片转为base64编码
利用以下一段简单的函数实现

 function imgChange(img) {
        const reader = new FileReader();
        reader.onload = function (ev) {
            var imgFile = ev.target.result; //imgFile就是图片的base64编码
            console.log(imgFile);

            base64url = imgFile.replace(/(.*)?,/, ''); //用正则消除前面的data之类的字符
            form = imgFile.substring(imgFile.indexOf("/") + 1, imgFile.indexOf(";")); //获取图片原本的格式
            console.log(imgFile);
            uploadimg(base64url, form); //上传
        }
        reader.readAsDataURL(img.files[0]);
    }
1

评论 (0)

取消