taltoooldtocode taltoooldtocode -4 years ago 150
Javascript Question

Javascript function is corrupting my .png image

I am developing a website and trying to upload an image to a local folder. I am successfully uploading the image, but I get an error when I try to open the image. Can anyone show me how to fix this problem?

Here is the error:
Could not load image'.PNG'. Fatal error reading PNG image file: not a PNG file.

Here is my partial:

<div class="form-group">
<label>Please Upload your Images</label>
<area href="./img" alt="this is a test">
<input type="file" class="form-control-file" ng-click="uploadImage()" id="uploadButton" multiple>

Here is my function:

$scope.uploadImage = function(){
var input = document.getElementById("uploadButton");
var text = document.querySelector("area");
var button = document.getElementById("submitButton");
var name;

input.onchange = function(e) {
var reader = new FileReader();
console.log("reader in CommandNewCtrl", reader);
reader.onload = function(event) {
console.log("event", event);
text.value = event.target.result;
button.disabled = false;
name = e.target.files[0].name;
console.log("name", name);
reader.readAsText(new Blob([e.target.files[0]], {
"type": "application/png"

button.onclick = function(e) {
var blob = new Blob([text.value], {
"type": "application/png"
console.log("blob", blob);
var a = document.createElement("a");
a.download = name;
console.log("a.download", a.download);
a.href = URL.createObjectURL(blob);
console.log("a.href", a.href);
text.value = "";
input.value = "";
button.disabled = true;

Answer Source

readAsText is not appropriate for binary data such as images. Try using readAsArrayBuffer or readAsDataUrl instead.

See this example that shows a preview image from a file selector.

You should also change the mimetype to image/png as Mark Schultheiss suggested.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download