0

Hi guys I'm working with Nuxt

And I have image saved on server as blob that I would like to display on client

My Component looks like this:

<template>
  <div class="product-page">
    <div class="product-image">
      <img data-image="black" :src="{imgSrc}" alt class="active" />
    </div>
    <div class="product-info">
      <h2>{{ product.name }}</h2>
      <h3>{{ product.price }}</h3>
      <div class="description">
        <p>The purposes of bonsai are primarily contemplation for the viewer, and the pleasant exercise of effort and ingenuity for the grower.</p>
        <p>By contrast with other plant cultivation practices, bonsai is not intended for production of food or for medicine. Instead, bonsai practice focuses on long-term cultivation and shaping of one or more small trees growing in a container.</p>
      </div>
    </div>
  </div>
</template>


<script>

export default {
  props: {
    product: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    imgSrc() {
      const src = URL.createObjectURL(this.product.images.data);
      return src;
    }
  }
};
</script>

Bu I keep getting following error:

URL.createObjectURL is not a function

Does anyone know what could be the problem ?

Loki
  • 725
  • 6
  • 29
  • In what [mode](https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-mode/) are you using nuxt ? And does the error happen on the browser or server ? – Pierre Said Mar 11 '21 at 00:04
  • Related GH issues with info: https://github.com/nuxt/nuxt.js/issues/4914 – manniL Mar 11 '21 at 07:36

1 Answers1

1

This error likely occurs on the server side, as Node does not support URL.createObjectURL(). Instead, you could create a data URL for your image in this format:

data:image/png;BASE64_OF_IMG_BLOB

where BASE64_OF_IMG_BLOB is computed from:

imgSrc would then look like this:

export default {
  computed: {
    imgSrc() {
      const isServer = typeof window === 'undefined'
      const blob = this.product.images.data
      const base64 = isServer ? blob.toString('base64') : btoa(blob)
      return 'data:image/png;base64,' + base64
    }
  }
}

Note the :src binding should be updated to remove the curly brackets:

<img :src="{imgSrc}"> ❌ brackets unnecessary
<img :src="imgSrc"> ✅
tony19
  • 64,135
  • 13
  • 95
  • 146