Voice Of The Rain
Voice Of The Rain

Reputation: 587

Assign Base64 string to an image in javascript

I already wasted a lot of time on a basic problem, I have a .cshtml razor view that have a model of type DataTable and this datatable have some TableRows with one column that stores an image byte array. how can I assign this model value to an image element in the view. this is what I've came up so far.

 var binaryData = @Convert.ToBase64String(Model.Rows[0][0] as Byte[]);
    var img = document.getElementById('ImgEle')
                      .setAttribute('src', "data:image/jpg;base64," + binaryData);

I'm receiving this error at chrome console window : Uncaught SyntaxError: Invalid regular expression flags

how can I fix this problem?

Edit:

Thanks to @hiltononline answer this is the code I'm ended up with and its working fine

var binaryData='@Convert.ToBase64String(Model.Rows[0][0] as Byte[])';
var img = document.getElementById("ImgEle");
img.setAttribute("src", "data:image/jpg;base64," + binaryData);

Hope this will help somebody.

Upvotes: 0

Views: 638

Answers (2)

hiltononline
hiltononline

Reputation: 536

The value of binaryData needs to be wrapped in single quotes to be treated as a string:

var binaryData='@Convert.ToBase64String(Model.Rows[0][0] as Byte[])';

An alternative could be to insert the model value in the setAttribute method directly:

var img = document.getElementById("ImgEle");
img.setAttribute("src", "data:image/jpg;base64,@Convert.ToBase64String(Model.Rows[0][0] as Byte[])");

Additionally, depending on how the data is stored, it may not need to be decoded again. You can double check the byte array is valid using an online decoder such as CodeBeautify's base64-to-image-converter

Upvotes: 2

jesus2099
jesus2099

Reputation: 85

I only know about how to display a base64 image string as tag in javascript so if your error is just at this level, good news — otherwise I cannot really help you with the first row (binaryData):

var binaryData = @Convert.ToBase64String(Model.Rows[0][0] as Byte[]);
var img = document.getElementById("ImgEle");
img.setAttribute("src", "data:image/jpg;base64," + binaryData);

I think you just forgot the name of the attribute (src) you wanted to set with setAttribute and that you messed up with the img variable assignation.

Upvotes: 0

Related Questions