可以知道data的類型為
data:[;base64],
可以知道data的類型為
data:[;base64],
/** | |
* @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") | |
} |