Skip to content

Instantly share code, notes, and snippets.

@shininghyunho
Last active August 6, 2022 17:06
Show Gist options
  • Save shininghyunho/10135dac1d62e3cf8eb6e010344d36a9 to your computer and use it in GitHub Desktop.
Save shininghyunho/10135dac1d62e3cf8eb6e010344d36a9 to your computer and use it in GitHub Desktop.
이미지 불러오기 예제 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST IMAGE</title>
</head>
<body>
<input id="userId"/>
<button id="enter">enter</button>
<br><img id="user-image">
<script>
/*
* 이미지 받아오기 sample
* response -> reader -> chunks -> blob -> image
* */
function requestUserImage(userId) {
const url='/api/v1/users/'+userId+'/image'
console.log('request '+url)
fetch(url, {
method: 'GET'
,}).then(response => {
console.log("response");console.log(response);
sync_process(response);
});
}
async function sync_process(response) {
const reader= response.body.getReader();
const chunks=await readAllChunks(reader);
const blob= new Blob(chunks);
document.getElementById('user-image').src=URL.createObjectURL(blob);
};
function readAllChunks(reader) {
const chunks=[];
return pump()
function pump() {
return reader.read().then(({ value, done }) => {
if (done){
return chunks;
}
chunks.push(value);
return pump();
});
}
}
document.querySelector("#enter").addEventListener("click",()=>{
const userId=document.querySelector("#userId").value;
console.log('request image, userId:'+userId);
requestUserImage(userId)
})
</script>
</body>
</html>
@shininghyunho
Copy link
Author

image

@shininghyunho
Copy link
Author

shininghyunho commented Aug 6, 2022

axios 를 사용한 방식

https://stackoverflow.com/questions/42785229/axios-serving-png-image-is-giving-broken-image

axios.get('/path/to/image.png', { responseType: 'arraybuffer' })
.then(response => {
      let blob = new Blob(
        [response.data], 
        { type: response.headers['content-type'] }
      )
      let image = URL.createObjectURL(blob)
      return image
    })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment