Skip to content

Instantly share code, notes, and snippets.

@nebaughman
Created November 9, 2019 11:09
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nebaughman/6af3d7fadbbbd1f641188079a545ae00 to your computer and use it in GitHub Desktop.
Save nebaughman/6af3d7fadbbbd1f641188079a545ae00 to your computer and use it in GitHub Desktop.
Load image with ajax (axios) as blob data in Vue component
<template>
<img ref="image" :src="blobUrl" @load="loaded"/>
</template>
<script>
import axios from "axios"
/**
* Load an image url as a blob
*/
async function load(src) {
const config = { url: src, method: "get", responseType: "blob" }
const response = await axios.request(config)
return response.data // the blob
}
/**
* Loads the image as a blob and createObjectURL().
* Set the img tag's src to the object url.
* Once the image is loaded, revoke the object url (avoid memory leak).
* Notice that the page can still show the image, but the src blob is no longer valid.
*/
export default {
data() {
return {
blobUrl: null,
}
},
props: {
src: {
type: String,
},
},
methods: {
loaded() {
if (this.blobUrl) URL.revokeObjectURL(this.blobUrl)
},
},
watch: {
src: {
immediate: true,
handler(src) {
if (!src) return
load(src).then(blob => {
this.blobUrl = URL.createObjectURL(blob)
})
},
},
},
}
</script>
<style scoped>
</style>
@3m1n3nc3
Copy link

This gist just saved my whole ass, I had to fork it 🤣

@martinpcarri
Copy link

Great implementation!

@notpidgey
Copy link

Greatest gist known to man! Thank you

@CheThePavle
Copy link

THANK YOU BRO!!!

@noho
Copy link

noho commented Jan 2, 2024

Thank you!!!

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