I am using fileReader for checking if a profile picture uploaded matches with my conditions. However, i don't have always the same result. Can you help me to fix that bug ?
Here my htlm code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>File API</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="page-wrapper">
<h1>Image File Reader</h1>
<div>
Select an image file:
<input type="file" id="fileInput">
</div>
</div>
<script src="images.js"></script>
</body>
</html>
Here my javascript/fileReader (images.js) code:
window.onload = function()
{
var width=0;
var height=0;
var exten= false;
var size = false;
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e)
{
var file = fileInput.files[0];
var imageType = /image.png/;
if (file.type.match(imageType))
{
exten = true;
var reader = new FileReader();
reader.onload = function(e)
{
var img = new Image();
img.src = reader.result;
img.onload = function()
{
width=this.width;
height=this.height;
}
}
reader.readAsDataURL(file);
}
else
{
exten= false;
}
if(width == 50 && height ==50)
{
size = true;
}
else
{
size = false;
}
//Here, we check that the image matches with png and 50*50px
if(size && exten)
{
alert('Your image is ok.');
}
else
{
if(!size && !exten)
{
alert('Image needs to be 50*50px and in png');
}
else
{
if(!size && exten)
{
alert('Image needs to be 50*50px');
}
else
{
if(size && !exten)
{
alert('Image needs to be in png');
}
}
}
}
});
}
Thank you for your help
You've to wait the execution of the img.onload event before checking width and height.
The code that's outside that event handler and that uses those properties should be moved inside it.
Related
I have validation in my angular controller to validate a image is a set size and is 1080x1920.
however evry image i try and upload I get error message
Error Uploading the image, make sure the resolution is 1080x1920px
even when I upload a image of the correct size. I am woundering if someone can spot a error in my code of why that may be ?
HTML
<div ng-controller="UpLoadImage">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}"/>
</div>
<label for="file">Select File</label>
<input ng-model="file" type='file' name='file' id='fileinput' base-sixty-four-input required onload='onLoad' maxsize='600'
accept='image/*' onchange='angular.element(this).scope().imageUpload(this)'/>
{{uploadError}}
<button>Add to array</button>
JavaScript
.controller('UpLoadImage', function ($scope, $http, $timeout) {
$scope.imageUpload = function(){
//
// $scope.uploadBtn = false;
$scope.errorActive = false;
$scope.success = false;
$scope.newImage = false;
var reader = new FileReader();
var input, file;
if (!window.FileReader) {
alert("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
$scope.errorActive = true;
$scope.uploadError = "Um, couldn't find the file input element.";
$scope.$apply();
}
else if (!input.files) {
$scope.errorActive = true;
$scope.uploadError = "This browser doesn't seem to support the `files` property of file inputs.";
$scope.$apply();
}
else if (!input.files[0]) {
$scope.errorActive = true;
$scope.uploadError = "Please select a file before clicking 'Upload'";
$scope.$apply();
}
else {
file = input.files[0];
size = file.size;
if(size < 650000){
var fr = new FileReader;
fr.onload = function(e){
var img = new Image;
img.onload = function(){
var width = img.width;
var height = img.height;
if(width == 1080 && height == 1920){
$scope.uploadError = '';
$scope.errorActive = false;
$scope.playingNow.background = e.target.result;
$scope.newImage = true;
$scope.uploadError = 'image uploaded';
$scope.$apply();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
}else{
$scope.errorActive = true;
$scope.uploadError = 'Error Uploading the image, make sure the resolution is 1080x1920px';
$scope.$apply();
}
};
img.src = fr.result;
};
fr.readAsDataURL(file);
}else{
$scope.errorActive = true;
$scope.uploadError = 'max file size supported is 650Kb please compress your image';
}
}
$scope.$apply();
};
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.stepsModel.push(e.target.result);
});
$scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
};
};
$scope.stepsModel = [];
})
As you are getting width = 1920 and height = 1080 so change your if condition :
if(height=== 1080 && width=== 1920){
// your code
}
if(width == "1080" && height == "1920"){
This should fix it.
This is the first time I am working with JavaScript modules. I am trying to upload an image and show it in a div under 'id="imageholder"'.
The error is:
uncaught type error :can't find property 'fileread' of undefined
HTML:
<html>
<body>
<div id='imageholder' style='width:100px;height:100px;border:1px solid black;position:relative;left:100px;'></div>
<input type='file' id='up' />
<script src='myscript.js'></script>
<script>
document.getElementById('up').addEventListener('change', FileUpload.files, false);
</script>
</body>
</html>
Here is the myscript.js module file which should return the object called FileUpload. But error is saying it is undefined. Why it is
undefined? It is long but it works when I don't use it like a module but all in a single file.
You can jump at the end and can see I am returning an object literal to FileUpload variable.
var FileUpload = (function(fileElement) {
var imageholder = document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback, callbackTwo) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log(header);
var imgtype = callback(url, header); // headerCallback
callbackTwo(imgtype, blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info = getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype, blob) {
var mimearray = ['image/png', 'image/jpeg', 'image/gif'];
if (mimearray.indexOf(mimetype) != -1) {
printImage(blob);
} else {
fileElement.value = '';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
// alert('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback, getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img = document.createElement('img');
img.setAttribute('src', e.target.result);
img.setAttribute('style', 'width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "image/pjpeg";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return (mimeType(headerString));
}
// Check for FileReader support
function fileread(event) {
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray = ['image/png', 'image/jpeg', 'image/gif'];
var file = event.target.files[0];
if (mimearray.indexOf(file.type) === -1 || file.size >= 2 * 1024 * 1024) {
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
fileElement.value = '';
file = null;
return false;
} else {
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
remoteCallback(file.name, file);
}
} else {
// File and Blob are not supported
console.log('file and blob is not supported');
}
}
return {
files: fileread
};
}(document.getElementById('up')))
it's working right as you provided it jsfiddle.net/fredo5n8/ here is the proof.
Are you sure you did not forget to wipe cache in your browser? If that's the case, try to run the code in incognito (private) window.
EDIT:
<html>
<body>
<div id='imageholder' style='width:100px;height:100px;border:1px solid black;position:relative;left:100px;'></div>
<input type='file' id='up' />
<script id='myscript' src='myscript.js'></script>
<script>
var script = document.getElementById('myscript');
var attachInputEvents = function () {
document.getElementById('up').addEventListener('change', FileUpload.files, false);
}
script.onload=attachInputEvents();
</script>
</body>
</html>
This way, you'll wait for the srcript to load(I guess that's the problem, cause locally on my machine even with separate files, it worked good hosted on WAMP server)
I putted my editor.html in a iframe using this code :
<iframe name= "iframeEditor" id="ifrm" src="editor.html" width="1000" height="500" frameborder="0"></iframe>
then, i have to access to an element in a script balise in my "editor.html" :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Diagram</title>
<script type="text/javascript" src="lib/jquery-1.8.1.js"></script>
<!-- I use many resources -->
<script>
function generatePNG (oViewer) {
var oImageOptions = {
includeDecoratorLayers: false,
replaceImageURL: true
};
var sResult = oViewer.generateImageBlob(function(sBlob) {
b = 64;
var reader = new window.FileReader();
reader.readAsDataURL(sBlob);
reader.onloadend = function() {
base64data = reader.result;
var image = document.createElement('img');
image.setAttribute("id", "GraphImage");
image.src = base64data;
document.body.appendChild(image);
}
}, "image/png", oImageOptions);
return sResult;
}
</script>
</head>
<body >
<div id="diagramContainer"></div>
</body>
</html>
I should access to image.src from the iframe that contain my editor.htm so i try with this code :
<script>
var if1 = document.getElementById("ifrm");
var fc = (if1.contentWindow || if1.contentDocument);
var img1 = fc.document.getElementById("GraphImage");
console.log(img1.src);
</script>
but i get an error : cannot read property "src" of null
You are running script that looks for image element before image is loaded, so it's not yet added to DOM.
move your script to separate function:
function yourScript() {
var if1 = document.getElementById("ifrm");
var fc = (if1.contentWindow || if1.contentDocument);
var img1 = fc.document.getElementById("GraphImage");
console.log(img1.src);
}
and run it at the end of onloadend callback:
function generatePNG (oViewer) {
var oImageOptions = {
includeDecoratorLayers: false,
replaceImageURL: true
};
var sResult = oViewer.generateImageBlob(function(sBlob) {
b = 64;
var reader = new window.FileReader();
reader.readAsDataURL(sBlob);
reader.onloadend = function() {
base64data = reader.result;
var image = document.createElement('img');
image.setAttribute("id", "GraphImage");
image.src = base64data;
document.body.appendChild(image);
yourScript(); // your script is run after appending image to body
}
}, "image/png", oImageOptions);
return sResult;
}
I have read some of the previous questions on this topic but I really need to be 100% sure!
Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?
I have tried several functions, here is one:
function readFile (path) {
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
while(!iStream.AtEndOfStream) {
document.body.innerHTML += iStream.ReadLine() + '<br/>';
}
iStream.Close();
}
readFile("testing.txt");
The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.
Is this possible without having my own server?
You can use a FileReader object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var x;
if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
else { x = new XMLHttpRequest(); }
function getdata() {
x.open('get', 'data1.txt', true);
x.onreadystatechange= showdata;
x.send(null);
}
function showdata() {
if(x.readyState==4) {
var el = document.getElementById('content');
el.innerHTML = x.responseText;
}
}
</script>
</head>
<body onload="getdata();showdata();">
<div id="content"></div>
</body>
</html>
I have been working on the following paradigm, in order to learn "how to drag an image from my desktop and drop it in my browser" works with Html 5. But after I drop the image, I just can't get the information about the image's actual width and height in the function handleFiles(files,n) where I alert it. Is this even possible?
Can anyone help me?
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="el-gr" lang="el-gr" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Files javascript upload with drag and drop</title>
</head>
<title>File(s) size</title>
</head>
<body>
<table>
<tr>
<td><input type="file" id="fileElem1" name="fileElem1" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_1" style="width:200px;height:100px;border:1px solid blue;z-index=10;">
<div id="preview1"></div>
</div>
</td>
<td><input type="file" id="fileElem2" name="fileElem2" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_2" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview2"></div></div></td>
<td><input type="file" id="fileElem3" name="fileElem3" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_3" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview3"></div></div></td>
</tr>
</table>
<input type="button" onclick="sendFiles()" value="send" >
<script>
var dropbox1,dropbox2,dropbox3;
dropbox1 = document.getElementById("dropbox_1");
dropbox1.addEventListener("dragenter", dragenter, false);
dropbox1.addEventListener("dragover", dragover, false);
dropbox1.addEventListener("drop", drop, false);
dropbox2 = document.getElementById("dropbox_2");
dropbox2.addEventListener("dragenter", dragenter, false);
dropbox2.addEventListener("dragover", dragover, false);
dropbox2.addEventListener("drop", drop, false);
dropbox3 = document.getElementById("dropbox_3");
dropbox3.addEventListener("dragenter", dragenter, false);
dropbox3.addEventListener("dragover", dragover, false);
dropbox3.addEventListener("drop", drop, false);
var fileElem1 = document.getElementById("fileElem1");
var fileElem2 = document.getElementById("fileElem2");
var fileElem3 = document.getElementById("fileElem3");
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var n=e.currentTarget.id.split("_");
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files,n[1]);
}
var filesforupload = new Array(null,null,null);
function handleFiles(files,n) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
alert(img.width); // <- HERE I NEED TO GET THE width of the image
img.style.zIndex=2;
img.style.position="absolute";
document.getElementById("dropbox_"+n).style.height="200";
document.getElementById("preview"+n).innerHTML = "";
document.getElementById("preview"+n).appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
filesforupload[n-1]=file;
//filesforupload.push(file);
//sendFile(file);
}
}
function sendFile(file) {
var uri = "upload.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText);
// handle response.
}
};
var reader = new FileReader();
fd.append('fileElem', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
function sendFiles(){
for (var i=0; i<filesforupload.length; i++) {
if(filesforupload[i]!=null)
sendFile(filesforupload[i]);
}
}
dropbox1.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
filesArray = event.dataTransfer.files;
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
}
</script>
</body>
</html>
Try it this way (updated with 100 ms timeout):
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
setTimeout(function() {
console.log(aImg.width); // right now file already loaded...
}, 100);
};
})(img);
http://jsfiddle.net/wVB3V/3/
anyway I found the following solution by adding an id to the image + onload function on the image like this
img.addEventListener('load', function() { alert(document.getElementById('test').width); /* ... */ }, false);
img.id="test";
The order does not matter since the load event fires after the img object gets appended.
Here is the complete code.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:og="http://ogp.me/ns#"
xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="el-gr" lang="el-gr" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>File(s) javascript upload with drag and drop</title>
</head>
<title>File(s) size</title>
</head>
<body>
<table>
<tr>
<td><input type="file" id="fileElem1" name="fileElem1" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_1" style="min-width:200px;height:100px;border:1px solid blue;z-index=10;">
<div id="preview1"></div>
</div>
</td>
<td><input type="file" id="fileElem2" name="fileElem2" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_2" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview2"></div></div></td>
<td><input type="file" id="fileElem3" name="fileElem3" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="dropbox_3" style="width:200px;height:100px;border:1px solid blue;"> <div id="preview3"></div></div></td>
</tr>
</table>
<input type="button" onclick="getthewidth()" value="send" >
<script>
function getthewidth(){
alert(document.getElementById('test').width);
}
var dropbox1,dropbox2,dropbox3;
dropbox1 = document.getElementById("dropbox_1");
dropbox1.addEventListener("dragenter", dragenter, false);
dropbox1.addEventListener("dragover", dragover, false);
dropbox1.addEventListener("drop", drop, false);
dropbox2 = document.getElementById("dropbox_2");
dropbox2.addEventListener("dragenter", dragenter, false);
dropbox2.addEventListener("dragover", dragover, false);
dropbox2.addEventListener("drop", drop, false);
dropbox3 = document.getElementById("dropbox_3");
dropbox3.addEventListener("dragenter", dragenter, false);
dropbox3.addEventListener("dragover", dragover, false);
dropbox3.addEventListener("drop", drop, false);
var fileElem1 = document.getElementById("fileElem1");
var fileElem2 = document.getElementById("fileElem2");
var fileElem3 = document.getElementById("fileElem3");
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var n=e.currentTarget.id.split("_");
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files,n[1]);
}
var filesforupload = new Array(null,null,null);
function handleFiles(files,n) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
img.addEventListener('load', function() { alert(document.getElementById('test').width); /* ... */ }, false);
img.id="test";
//alert(document.getElementById('test').id);
// alert(img.width); // <- HERE I NEED TO GET THE width of the image
img.style.zIndex=2;
img.style.position="absolute";
//document.getElementById("dropbox_"+n).style.height="200";
document.getElementById("preview"+n).innerHTML = "";
document.getElementById("preview"+n).appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
filesforupload[n-1]=file;
//filesforupload.push(file);
//sendFile(file);
}
}
function sendFile(file) {
var uri = "upload.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText);
// handle response.
}
};
var reader = new FileReader();
fd.append('fileElem', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
function sendFiles(){
for (var i=0; i<filesforupload.length; i++) {
if(filesforupload[i]!=null)
sendFile(filesforupload[i]);
}
}
dropbox1.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
filesArray = event.dataTransfer.files;
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
alert(out);
}
</script>
</body>
</html>