1

I use GitHub API with JS to create a small script #Create,#Delete,#Edit

E.g:

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);
        });
    }

It works very well with uploaded text files But the problem is that I want to upload a picture, for example, or a video on Github

when I upload the image it looks like this :

�PNG

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

...

update 1

the code which reads files from input

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]);
            }
    } 
}

Is there any way to upload photos and other files using javascript & Github API?

Greetings

zahaby
  • 33
  • 10

1 Answers1

2

The issue is the way you encode the image to base64. In your readURL function use :

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]);
  }
}

which gives the image base64 encoded & use the solution from this post to strip the file type. The full code :

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>
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
  • 1
    this is very helpful , thank you so much ,,, But I think if we replace Line15 with this: `(/data:\w*\/\w*;base64,/gm,'')` will be better – zahaby Jan 09 '18 at 08:02
  • @zahaby you're right I've updated with the solution from [this post](https://stackoverflow.com/questions/24289182/how-to-strip-type-from-javascript-filereader-base64-string) regarding this – Bertrand Martel Jan 09 '18 at 09:16