i get a broken image icon when i want to display a blob image with createObjectURL :
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 :
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 ?
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/*'});