使用ajax上传图像的GitHub API

时间:2018-01-07 08:42:57

标签: javascript ajax api github github-api

我使用GitHub API和JS创建一个小脚本#Create#Delete#Edit

例如:

function createfile(/* url , */ fileName,fileMessage,fileContent){
            var filename = /* "firstfile.txt" */ fileName;
            var filemessage = /* "uploading a file" */ fileMessage;
            var filecontent = /* "The data of the file2." */ fileContent ;
        var basecontent = btoa(filecontent);
        var apiurl = "https://api.github.com/repos/el3zahaby/testet/contents/{+path}".replace('{+path}',filename);
        var filedata = '{"message":"'+filemessage+'","content":"'+basecontent+'"}';

        $.ajax({ 
            url: apiurl,
            type: 'PUT',
            beforeSend: function(xhr) { 
                xhr.setRequestHeader("Authorization", "Basic " + btoa("USERNAME:PASSWORD")); 
            },
            data: filedata
        }).done(function(response) {
            console.log(response);
        });
    }

它适用于上传的文本文件 但问题是我想上传一张图片,例如Github上的视频或

当我上传图片时,它看起来像这样:

�PNG

IHDRHHU��G cHRMz&�����u0�`:�p��Q<bKGD�������tIME�   
/��p�IDATx�͜wx�E��?��rs��BK!���D���}�?��
]uu��,��.�bߵ
TT��CH��rs����ǽ� 

...

更新1

从输入中读取文件的代码

function readURL(input) {
    if (input.files && input.files[0]) {
        //console.log(input.files[0].getAsBinary());
       // createfile(input.files[0].name,"uploading a file", input.files[0])


        var reader = new FileReader();
        reader.onload = function (e) {
            $('#falseinput').attr('src', e.target.result);
            $("#v1").html('<source src="'+ e.target.result +'" type="video/mp4"></source>' );

            $('#base').val(e.target.result);
            $('#base1').val(btoa(unescape(encodeURIComponent(reader.result))));
            var content = e.target.result;
            createfile(input.files[0].name,"uploading a file", unescape(encodeURIComponent(content)))
        };
        if (allow.binary.indexOf(input.files[0].type) === -1) {
                alert(input.files[0].type);
                reader.readAsText(input.files[0],"UTF-8");
            }else{
                reader.readAsDataURL(input.files[0]);
            }
    } 
}

有没有办法使用javascript&amp;上传照片和其他文件? Github API?

问候

1 个答案:

答案 0 :(得分:0)

问题是您将图像编码为base64的方式。在readURL函数中使用:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onloadend = function() {
      var base64result = reader.result.substr(reader.result.indexOf(',') + 1);
      createfile(input.files[0].name, "uploading a file", base64result)
    }
    reader.readAsDataURL(input.files[0]);
  }
}

给出了图像base64编码&amp;使用this post中的解决方案来删除文件类型。完整代码:

const nameWithOwner = 'el3zahaby/testet';
const token = 'YOUR_ACCESS_TOKEN';

function handleFileSelect(evt) {
  readURL(evt.target);
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onloadend = function() {
      var base64result = reader.result.substr(reader.result.indexOf(',') + 1);
      createfile(input.files[0].name, "uploading a file", base64result)
    }
    reader.readAsDataURL(input.files[0]);
  }
}

function createfile(fileName, fileMessage, fileContent) {
  var apiurl = "https://api.github.com/repos/" + nameWithOwner + "/contents/" + fileName;
  var filedata = JSON.stringify({
    "message": fileMessage,
    "content": fileContent
  });

  $.ajax({
    url: apiurl,
    type: 'PUT',
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization", "Token " + token);
    },
    data: filedata
  }).done(function(response) {
    console.log(response);
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>