[Vuejs]-Vue.js, show image dynamically after downloading it

2๐Ÿ‘

โœ…

By the great help of @Shivam Singh and this handy git repo
download-file.js,
I could solve the problem.

Response type of the request (Axios request) should be
responseType: โ€˜blobโ€™
And after receiving data from server, I simply used this line of code below to generate a DOM string and then place it as src to an image tag:

const imageUrl = window.URL.createObjectURL(new Blob([response.data]))

<img :src="imageUrl ">

According to this link URL.createObjectURL method, creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created.

๐Ÿ‘คAli Afsahnoudeh

2๐Ÿ‘

new Vue({
  el: '#app',
  
  data () {
    return {
      src: null
    }
  },
 
  mounted () {
    let self = this
    fetch("https://thumbs.dreamstime.com/z/freely-accessible-examination-exposition-mosaic-ar-figures-mosaic-st-petersburg-russia-june-freely-accessible-119320551.jpg")
    .then((response) => {
      response.blob().then(blobResponse => {
        let reader = new FileReader();
        reader.readAsDataURL(blobResponse); 
        reader.onloadend = function() {
          let base64data = reader.result; 
          let img = document.createElement('img')
          img.src = base64data  
          self.$refs['img-container'].appendChild(img)
        }
      })
    })
  }
})
img {
  height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div ref="img-container"></div>
</div>
๐Ÿ‘คShivam Singh

Leave a comment