Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  134] [ 4]  / answers: 1 / hits: 23198  / 7 Years ago, fri, november 24, 2017, 12:00:00

I have a vue file like this,





export default {
data(){
return{
info: {
name: '',
image: '',

},
errors: []
}
},

created: function(){
this.getInfo();
},

methods: {
getInfo: function(){
this.info.name = response.data.results[0].name;
this.info.image = response.data.results[0].image;
}
}
}





I am passing data from this file into a child Vue component. The child component is as follows,





<template>
<div class=ui items>
<div class=item>
<div class=ui small image>
{{info.image}}
</div>
</div>
</div>

</template>

<script>
export default{

props:['info']

}
</script>





My image is stored as a blob in a MySQL database. When I run my application, the image appears as binary data on the UI. The object appears like this,



JSON



Can anybody here help me in displaying the image? Thank you very much!


More From » html

 Answers
29

What you want is a data url. You will need to convert the byte array to base64. There is no way to use the raw bytes. Perhaps do this in a computed property, using one of the byte array to base64 functions.



Markup



<img :src=dataUrl>


Behaviour (untested!)



computed : {
dataUrl(){
return 'data:image/jpeg;base64,' + btoa(
new Uint8Array(this.info.image)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
}
}


Search your conscience. This is really not a good idea :-) Sending images as a JSON encoded byte array is something I've never seen, and will be about, guessing, 10x larger on the wire than the binary image.
Images in the DB are an antipattern. Images in JSON work, but they should be encoded as base64 strings in the JSON. Even then, they reduce the readability of the JSON, and can bury tools like Postman. Data urls are much slower to load than regular urls. Even with images in the DB, if you control your api, you can gain a lot by making image apis that return just the byte array, with an application/jpeg mime type.


[#55850] Tuesday, November 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennie

Total Points: 593
Total Questions: 102
Total Answers: 106

Location: Federated States of Micronesia
Member since Fri, Sep 16, 2022
2 Years ago
jennie questions
;