Skip to content

Instantly share code, notes, and snippets.

@CarsonSlovoka
Last active July 19, 2021 11:56
Show Gist options
  • Save CarsonSlovoka/57df33c68a48bfc462879bd6ca12a3d1 to your computer and use it in GitHub Desktop.
Save CarsonSlovoka/57df33c68a48bfc462879bd6ca12a3d1 to your computer and use it in GitHub Desktop.
get the image from some repository of GitHub.
/**
* @param {int} solutionNumber: I provide two solutions both can achieve.
* @param {string} owner
* @param {string} repo
* @param {string} path
* @param {string} branch: branch name or you can use SHA1
* @param {string} token: Used while your repository is private. https://github.com/settings/tokens
*/
async function ShowGithubImg(solutionNumber, owner, repo, path, branch = "master", token = "") {
const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch}`, {
// method: "GET",
headers: {
accept: 'application/vnd.github.v3.raw',
// authorization: `token ${token}`
}
})
if (!response.ok) {
const errMsg = await response.text()
throw Error(`${response.statusText} (${response.status}) | ${errMsg} `)
}
const responseBlob = await response.blob()
const img = document.createElement('img')
switch (solutionNumber) {
case 1:
img.src = URL.createObjectURL(responseBlob)
break
case 2:
let uriData = ""
blob2bas64 = async (blob) => {
const promise = new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = function () { // use promise to wait until onload finished
console.log(this.result) // you can see its media type is: application/vnd.github.v3.raw // https://docs.github.com/en/rest/overview/media-types
uriData = this.result // <--- `this.result` contains a base64 data URI
resolve()
}
reader.readAsDataURL(blob)
})
await promise
}
await blob2bas64(responseBlob)
img.src = `${uriData}` // "data:image/png;base64,iVBORw0KGgoA...", "data:application/vnd.github.v3.raw;base64,AAABAAQAEBAAAA...", etc.
break
}
document.querySelector(`body`).append(img)
}
for (const solutionNumber of [1, 2]) {
ShowGithubImg(solutionNumber, "CarsonSlovoka", "excel", "app/urls/static/app.ico", "807dd79")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment