0

i get a broken image icon when i want to display a blob image with createObjectURL :

enter image description here

I provide a Uint8Array to the first parameter of the blob object (data), here is the js code :

const photo = $('.photo');
console.log('js working');
const blobDiv = $('.blobDiv');
const form = document.getElementById('form');

const file = document.getElementById('file');
const etat = $('#etat').text();



if(etat === 'true'){
  console.log('true');
  const data = $('.blob').text();
  console.log('Uint8Array : ' + data);
  const blob = new Blob([data], {type: 'image/*'});
  console.log('blob size: ' + blob.size);
  console.log('blob type: ' + blob.type);
 

  const img = document.createElement("img");
  
  img.src = URL.createObjectURL(blob);
  img.width = 200;
  img.height = 200;
  
  img.onload = () => {
    URL.revokeObjectURL(img.src);
  };
  
photo.append(img);

};

HTML :

         <body>
        <form action="/upload" method="post" id="form" enctype='multipart/form-data'>
            <input type="file" id="file" name="file" accept="image/*" multiple ><br>
            <input type="text" id="comments" placeholder="File comments"><br>
            <button type="submit" id="buttonSubmit">Upload file</button>
        </form>
        
        
        
        
        <% if (upload) { %>
            <h2> File uploaded</h2>
            <p id="etat">true</p>
            <div class="container">
                <div class="blob">
                    <%= blobArray %>
                </div>
                <div class="photo">
                </div>
                
            </div>
           
            
            <%} else if(!upload) { %>
                <p id="etat">false</p>
            <h2> No files uploaded yet </h2>
            <% } %>
        
        
        <script src="fu.js" async defer></script>
    </body>
</html>

Result in the console :

enter image description here

Input form is processed behind by the server code and returning a Uint8array needed for the blob, as you can see on the js console, the array is successfully passed

Why do i have this broken image icon ?

Kogami997
  • 33
  • 5
  • Why do you use `revokeObjectURL`? – Konrad Jun 06 '23 at 20:11
  • "Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is done by calling the URL.revokeObjectURL() method and passing in the object URL string as specified by img.src." - https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications#example_using_object_urls_to_display_images – Kogami997 Jun 06 '23 at 20:21

1 Answers1

2

data is not Uint8Array its text. You can convert it to Uint8Array by splitting it into an array and passing that to a Uint8Array constructor.

const data = $('.blob').text();
const ui8Array = new Uint8Array(data.split(','))
const blob = new Blob([ui8Array], {type: 'image/*'});
Musa
  • 96,336
  • 17
  • 118
  • 137