Github API – How to upload a file

Github API – How to upload a file

Hey folks – I spent almost an entire day trying to look up ways to upload either an image or a pdf file to a github repo using curl commands, and ultimately attach it to an issue.

There are worthless and pointless blogs out there that do nothing but waste everyone’s time, so here’s a simple solution.

Unfortunately, there’s no direct way to attach a file to an issue, but in two steps it can be accomplished. In my example, I’m going to upload a sample pdf file to my a test repo, and attach it to an issue.

Step 1: Upload a file to a repo

curl -i -X PUT -H ‘Authorization: token 98xxxxxxxxxxxxxxxxxxxxxxxe2’ -d
‘{“message”: “uploading a sample pdf”,
“content”:”bXkgbm……………………………..”
}’ https://api.github.com/repos/batman/toys/contents/sample.pdf

Notice: the “content” property needs to be base64 encoded and only then the API will let you upload it to your repo. 
To achieve this, you could just encode it using this tool online https://www.freeformatter.com/base64-encoder.html
Which will give you a long string of characters, after which just copy/paste the string into the “content” property, and ran the above curl command.  and BAM, there you go. You have your pdf file in your repo.
 
 
Step 2: Attach the uploaded PDF to an Issue
 

curl -i -H ‘Authorization: token 8xxxxxxxxxxxxxxxxxxxxxxxe2’ -d ‘
{“body”: “[sample.pdf]
(https://github.com/batman/toys/blob/master/sample.pdf)“}’
https://api.github.com/repos/batman/planning/issues/99

 
Essentially, you’r updating a body of the issue with the reference to the uploaded file. And BAM, your issue has been updated with the link to your pdf file.
 
And that’s it folks….
 
In conclusion, I’m using a pdf example here, but you can run the identical steps for any of these formats github allows. Keep in mind, they all need to be base64 encoded before making that curl command.
 
Reference links: