2

I'm trying to display a raw image which has been formatted to base64 into an img element with javascript. I already have my base64 but cannot make it displaying as raw image, what is wrong with the code?

here is the code.

 $.each(post.JobPictures, function (i, pictures) {
                                            if (pictures != null) {
                                                var decodedString = atob(pictures.JobImageContentBytes)
                                                var img = new Image();
                                                img.src = ("data:image/jpg;base64,"+ decodedString);

                                                `<div class="separate-pic">
                                                    <img class="posted-pic" src="`+img+`" alt="" />
                                                </div>`
                                             }
                                    })

UPDATE THIS IS USING MAP NOW, BUT IT DOES NOT GO IN AT ALL

$.ajax({
        url: '@Url.Action("SearchByCategory", "AllJobs")',
        type: 'GET',
        contentType: 'JSON',
        data: { category: categoryId },
        success: function (posts) {

            $(".job-container").html("");
            //$(".job-container").load(" .job-container");

            $.each(posts.FindJobs, function (i, post) {

                var newdate = new Date(post.PostedDate + 'Z');
                var day = newdate.getDate();


                $(".job-container").append(`


                        <li class="separate-job" id="All-Jobs-Id" value="` + post.jobId + `">
                            <div class="content-li-All-Jobs">
                                <h2 class="content-li-All-headline" id="headline-for-Update">`+ post.Headline + `</h2>
                                <a class="btn btn-success bid-for-job" value="`+ post.jobId + `" href="#">Bid now</a>
                                <div class="user">
                                    <blockquote class="blockquote">
                                        <p class="mb-0">
                                            <div class="about-job">`+ post.About + `</div>
                                        </p>
                                        <div class="blockquote-footer">
                                            <cite>-`+ post.Username + `</cite>
                                        </div>
                                    </blockquote>
                                </div>
                                <div class="pictures-li">
                                   `+ $.map(post.jobPictures, function (i, pictures) {
                        if (pictures != null) {
                            var decodedString = atob(pictures.JobImageContentBytes)
                            return `<div class="separate-pic">
                <img class="posted-pic" src="data:image/jpg;base64,${decodedString}" alt="" />
            </div>`;
                        }
                    }).join("") + `
                                </div>

                                <div class="job-date-li">
                                    Posted `+ newdate.getDate() + ` ` + newdate.getMonth() + ` ` + newdate.getFullYear() + 
                `

                                </div>
                                <div class="-job-town">Area | <span class="city">`+ post.JobCity+`</span></div>
                            </div>
                        </li>



                 `)

            });



        }
    });

This is my entire ajax call which I make to a controller in order to get all jobs which are in certain category and create those divs and assign the relevant data to them

here is the image that shows that the object/arrays are not empty

enter image description here

enter image description here

11
  • @Taplar sorry, my bad, I was using the following code snippet in an .append method. Now it is more clear? Commented May 6, 2019 at 19:52
  • So, basically, I have an array with some bytes and I loop through the items to display the img and create div+ img element. How else should I do it? I`m really confused Commented May 6, 2019 at 19:54
  • @Taplar I don't want to do anything with it - All I want to do is to display the img inside a div and depending on how long the array is it will generate those divs with those images. Commented May 6, 2019 at 20:06
  • I will update the post to see the whole append and what`s in it... Commented May 6, 2019 at 20:15
  • 1
    contentType: 'JSON', is wrong, it should be dataType: 'json' Commented May 6, 2019 at 20:40

1 Answer 1

3

$.each() returns the value of its first argument, so this will by equivalent to just writing:

+ post.JobPictures + 

You need to use $.map(), the callback function needs to return something, and then you can concatenate the array of results into a string with .join().

You shouldn't try to concatenate an img element directly into the string. Instead, substitute the base64 string into the src attribute.

The data in `JobImageContentBytes is already encoded as base64, you don't need to call anything to encode it.

JobPictures has an uppercase J at the beginning.

The arguments to the callback function of $.map should be in the order element, index.

+ $.map(post.JobPictures, function (pictures) {
    if (pictures != null) {
        return `<div class="separate-pic">
                    <img class="posted-pic" src="data:image/jpg;base64,${pictures.JobImageContentBytes}" alt="" />
                </div>`;
     }
}).join("") + 

BTW, the point of using template literals is so you don't need to end the string and use + to concatenate an expression, you can embed the expression with ${}. So don't write

src="`+img+`"

Instead write

src="${img}"
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.