我正在开发一个网站,并尝试将图像上传到本地文件夹。我成功上传了图片,但是当我尝试打开图片时收到错误。有谁能告诉我如何解决这个问题?
这是错误: 无法加载图片' .PNG'。读取PNG图像文件时出现致命错误:不是PNG文件。
这是我的部分内容:
<div class="form-group">
<label>Please Upload your Images</label>
<br>
<area href="./img" alt="this is a test">
<br>
<input type="file" class="form-control-file" ng-click="uploadImage()" id="uploadButton" multiple>
</div>
这是我的功能:
$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) {
e.preventDefault();
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);
document.body.appendChild(a);
a.click();
text.value = "";
input.value = "";
button.disabled = true;
document.body.removeChild(a);
}
};
答案 0 :(得分:1)
readAsText
不适用于图像等二进制数据。请尝试使用readAsArrayBuffer或readAsDataUrl。
请参阅this example,其中显示了文件选择器中的预览图像。
你也应该像Mark Schultheiss所建议的那样将mimetype更改为image/png
。
答案 1 :(得分:0)
非常感谢塞缪尔和马克!这段代码正常运作!
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.readAsArrayBuffer(new Blob([e.target.files[0]], { //was readAsText
// "type": "application/png"
"type": "image/png"
}));
};
button.onclick = function(e) {
e.preventDefault();
var blob = new Blob([text.value], {
"type": "image/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);
document.body.appendChild(a);
a.click();
text.value = "";
input.value = "";
button.disabled = true;
document.body.removeChild(a);
}
};