javascript not getting correct image width and height - javascript

I have added multiple image upload to my site using HTML api's. I have to test each images while uploading, whether they tall (height>width) or long(height
<script type="text/JavaScript">
function filesProcess(files)
{
var shape=document.getElementById('shapeval').value;
for( var i = 0; i < files.length; i++)
{
file = files[i];
if(!file.type.match(/image.*/))
{
alert('File name '+file.name+' is not allowed! Please try again!');
window.location.reload(true);
continue; //Jump forward to the next file...
}
else
{
var iw=document.images[i].width;
var ih=document.images[i].height;
var n=document.images[i].name;
if(shape="tall")
{
alert("width:"+iw+" and height:"+ih);
}
else
{
alert("width:"+iw+" and height:"+ih);
}
continue;
}
}
}
</script>
HTML
<form action="upload.php/" method="post" enctype="multipart/form-data" name="uploadForm" onsubmit="return(validate());">
<input type="file" id="files" name="files[]" multiple onchange="filesProcess(this.files);" accept="image/*"/>
<input type="hidden" name="shapeval" id="shapeval" value="tall" />
</form>
Using this code width and height are displaying, but the value of them are not correct. Most of the time it's showing 182 and 51 for both type of images; So I couldn't recognize the images are tall or long? Where I did mistake? Am I missing something?Anyone have any idea??
Thanks!

As far as I know, you can't get the height or width of an image you are about to upload thru Javascript. You will need to upload it to the server and then use PHP (or any other server-side scripting language) to get information about the image. Try the PHP function getimagesize(), it should give you the information you need.
If you're wanting to process the image inline and kick back information to the user, I would suggest submitting the form with AJAX and using the response data.

Related

JS Change function working only first time

In this, I have a give module (wordpress plugin for fundraiser) and I have integrated the file upload
https://www.mamafrica.it/26964-2/
I have add a java script in order to check the file size and file type, but this work only until I not change the payment method.
For example:
After load page, if I load file > 500KB or different from pdf or jpg, error message appears under the file upload area.
If I switch to "Donation by bank transfer" the form change (an information text appears before file upload area and the form fields are cleaning).
Now, if I choose another file > 500KB (or not pdf or jpg) the error message not appears.
The 'change', function in javascript is not invoked.
This is the javascript
<script>
var inputElement = document.getElementById("fileToUpload")
inputElement.addEventListener('change', function(){
alert("QUI");
var error = 0;
var fileLimit = 500; // In kb
var files = inputElement.files;
var fileSize = files[0].size;
var fileSizeInKB = (fileSize/1024); // this would be in kilobytes defaults to bytes
var fileName = inputElement.value;
idxDot = fileName.lastIndexOf(".") + 1;
extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
document.getElementById("error").innerHTML = "";
document.getElementById("filenamecheck").innerHTML = inputElement.value;
if (extFile=="jpg" || extFile=="pdf"){
console.log("Type ok");
} else {
error = 1;
document.getElementById("error").innerHTML = "Solo file .pdf o .jpg";
document.getElementById("fileToUpload").value = "";
}
if (error == 0) {
if(fileSizeInKB < fileLimit) {
console.log("Size ok");
} else {
console.log("Size not ok");
document.getElementById("error").innerHTML = "Massima grandezza file: " + fileLimit + "KB";
document.getElementById("fileToUpload").value = "";
}
}
})
</script>
This the file upload area
<div class="file-uploader">
<input id="fileToUpload" name="fileToUpload" type="file" accept=".pdf,.jpg"/>
<label for="file-upload" class="custom-file-upload">
<i class="fas fa-cloud-upload-alt"></i>Clicca per scegliere il file
<span name="filenamecheck" id="filenamecheck">test</span>
</label>
<p id="error" style="color: #c00000"></p>
</div>
Someone can help me?
UPDATE: The correct URL is https://www.mamafrica.it/26964-2/
UPDATE SOLVE
I have found a solution for my problem!!
First time, I have insert the javascript code after the end of form tag and the refresh work only on elements inside of form tag.
Using a wordpress hook (in function.php) i have insert the javascrip code immediatly after the input tag, inside of the form tag, in this way, the form refresh, reload also the javascript.
Thank you all!
Regards,
Marco
UPDATE
I have found a solution for my problem!!
First time, I have insert the javascript code after the end of form tag and the refresh work only on elements inside of form tag. Using a wordpress hook (in function.php) i have insert the javascrip code immediatly after the input tag, inside of the form tag, in this way, the form refresh, reload also the javascript.
Thank you all!
Could be that you are using:
inputElement.addEventListener
That might be only triggered once.
You might use something in a form as simple as:
onSubmit="return MyFunctionName"
That is being used in form validation for years.
I hope this helps,
Ramon

How to delete the specific value of an “input type=file” multiple

I am using input type='file' with multiple file and one with single file. like,
//single image
//IMAGE_TYPES is constant and defined with:define('IMAGE_TYPES',array('main','floor','bedroom1','bedroom2','bedroom3','kitchen','reception','garages','epc','other'));
#foreach(IMAGE_TYPES as $images)
#if($images!='other')
<div class="col-sm-10">
<input type="file" class="form-control" id="{{$images}}_image" name="{{$images}}_image" accept="image/*" placeholder="<span> <i class='fa fa-plus-circle'></i>Click here or drop files to upload</span>"/>
</div>
#else
//multiple
<div class="col-sm-10">
<input type="file" class="form-control" id="other_images" name="other_images[]" accept="image/*" placeholder="<span> <i class='fa fa-plus-circle'></i>Click here or drop files to upload</span>" multiple />
</div>
#endif
#endforeach
Now, I validating it with jquery like,
var image_type ='<?=json_encode(IMAGE_TYPES);?>';
image_type = JSON.parse(image_type);
var max_image_size = 2;
$.each(image_type, function( index, value ) {
if (value!='other') {
$('#'+value+'_image').bind('change', function() {
var a=(this.files[0].size);
var ValidImageTypes = ["image/jpeg", "image/png"];
if ($.inArray(this.files[0].type, ValidImageTypes) < 0) {
show_notification('error','Only .jpg/.jpeg and .png file allowed. Please select other image.');
var file = document.getElementById(value+'_image');
file.value = file.defaultValue;
return false;
}
else{
if (Math.round(a / (1024 * 1024)) > max_image_size) {
show_notification('error','Image is Greater than '+max_image_size+'MB. Please select smaller image.');
var file = document.getElementById(value+'_image');
file.value = file.defaultValue;
return false;
}
else
{
preview_main_image(value);//won't matter
}
}
});
}
else{
$('#other_images').bind('change', function() {
$('div.add_preview').remove();//won't matter
for (var i = 0; i < $("#other_images").get(0).files.length; i++) {
var a=(this.files[i].size);
var name = this.files[i].name;
var ValidImageTypes = ["image/jpeg", "image/png"];
if ($.inArray(this.files[i].type, ValidImageTypes) < 0) {
show_notification('error','Image '+name+' is Not allowed. Only .jpg/.jpeg and .png file allowed. Please select other image.');
}
else{
if (Math.round(a / (1024 * 1024)) > max_image_size) {
show_notification('error','Image '+name+' is Greater than '+max_image_size+'MB. Please select smaller image.');
}
else
{
$('#other_image_preview').append("<div class='col-md-2 p_3 add_preview'><img class='img-responsive' src='"+URL.createObjectURL(event.target.files[i])+"'></div>");//won't matter
//preview_detail_images(value);
}
}
}
});
}
});
Now, my question is when i am using single image if image is not fitting in validation then i delete it's value from input type='file' using, this code
var file = document.getElementById(value+'_image');
file.value = file.defaultValue;
return false;
But when i select multiple image and if any image is not fitting in validation then how can i remove that particular image from input type='file'.
Please help me
The file will have to come in input element for the input change handler to work. You can validate there and show only valid files in preview, ignoring the invalid ones.
You can check jQuery file uploader: https://blueimp.github.io/jQuery-File-Upload/
You can keep your input invisible over another div which is your preview and show the uploaded files in the div to give the illusion to the user that you are discarding invalid files.
The answer is simple: You can't. Value of files property of an <input type="file"> is a FileList. This one is immutable for security reasons. Also the files property is readonly and you can't construct a FileList.
The best you could do is to a) show a validation error to user and ask him to remove the file; b) ignore the file on processing (e.g. preview, uploading to server).
As #mixable already pointed out in his answer, validation should also be done on backend.
You can just ignore this file type on the server when processing the uploaded files. This is the better solution, because it is more secure. When you rely on JavaScript, it is very easy to send manipulated data to your server and upload filetypes of other images (or even scripts like js, php, ...).
Hi please check out my fiddle. I created a form which can be automatically submitted with valid files.
https://jsfiddle.net/2ah5r0bj/135/
What I did is basically:
var form = document.getElementById("myAwesomeForm");
var formDataToUpload = new FormData(form);
...
for (var i = 0; i < validFiles.length; i++) {
formDataToUpload.append("other_images[]", validFiles[i], validFiles[i].name);
}
var xhr = createCORSRequest("POST", "https://httpbin.org/post");
xhr.send(formDataToUpload);

I am facing Issue in size of file Validation in magento 1

I have an issue in validating a file in magento form validator,
i have custom validation code for file size like this.
Validation.add('validate-filesize', 'Upload file should be less than 2MB',function(v,elem) {
var file = elem.files;
var fileSize = file[0].size;
if(fileSize <= 2000000){
return true;
}
else{
return false;
}
});
and in my form there are two file filds.
above validation code is working fine for this field.
<input type="file" id="file1" name="file1" value="" class="input-text required-entry validate-filesize">
but it is failing to validate below field
<input type="file" id="file2" name="file2" value="" class="input-text validate-filesize">
The error doesn't lie in the library, but in your validator callback function.
You are checking the size of the file using the following code
var fileSize = file[0].size
But when the user doesn't upload any files, the variable file[0] is undefined. Thus when you do file[0].size, it throws an error saying Cannot read property 'size' of undefined. And that's why further processing of your code stops and you don't get the desired message.
A good way of doing it would be to check if the user has uploaded any files before checking it's size, like so.
var file = elem.files;
if(file.length == 0) return true; // all is good if user didn't upload any file
//go ahead with the rest of the code otherwise
var fileSize = file[0].size;
if(fileSize <= 2000000){
return true;
}
else{
return false;
}

Dimensions validation for image client side

The website that I'm working on has an option to upload images, but I must validate the image's dimensions (width, height) before uploading to the server side or before submitting.
For example the image must be 250x250, otherwise an alert occurs and the user can't upload the image, here's a part of my code:
<form action="upload_file.php" method="post" enctype="multipart/form-data" name = "upload" id="insertBook" onSubmit="return validateImage();">
<input type="file" name="image" value="upload" id = "myImg">
<input type="submit" name = "submit">
</form>
validateImage function now just checks for the extensions, I want it also to check for the dimensions.
Here's the code so far:
function validateImage(){
var allowedExtension = ["jpg","jpeg","gif","png","bmp"];
var fileExtension = document.getElementById('myImg').value.split('.').pop().toLowerCase();
var isValidFile = false;
for(var index in allowedExtension) {
if(fileExtension === allowedExtension[index]) {
isValidFile = true;
break;
}
}
if(!isValidFile) {
alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
}
return isValidFile;
}
Thank you! :)
function validateImage(){
var isValidFile = false;
var image = document.getElementById('myImg');
var allowedExtension = ["jpg","jpeg","gif","png","bmp"];
var srcChunks = image.src.split( '.' );
var fileExtension = srcChunks[ srcChunks.length - 1 ].toLowerCase();
if ( image.width !== image.height !== 250 ) {
console.log( 'Size check failed' );
return false;
}
for(var index in allowedExtension) {
if(fileExtension === allowedExtension[index]) {
isValidFile = true;
break;
}
}
if(!isValidFile) {
alert('Allowed Extensions are : *.' + allowedExtension.join(', *.'));
}
return isValidFile;
}
Related to this topic
As I said in my comment, you can check for the size on the client-side but it's unsafe as the javascript may be bypassed, and your validation would serve no purpose. If someone really wants to upload a file that is 5Go, he just have to redefine your check function.
A server side validation isn't accessible by the client. Moreover depending on your backend and your image handling (Are you handling it like a simple file ? Or do you have some lib to work with images ?), you may find some methods to help you with image dimensions. For example in python I use PIL (Pillow for 3.x version) to check for image information, size, dimension, content, check if it's a real file or not... Actually it's really easy to upload a corrupted file that contains some php code in it (for example) so you should be really careful when you let users upload content to your server.

File Upload Form Field Validation

This is a trivial question, but for some reason I am having trouble with it.
I have HTML for uploading a file such as the following.
<input type="file" name="settings">
And all I need to do is check when the form is submitted that a value has been selected.
I dont need help with the code for the form submission, I just need help since I am guessing
you are unable to validate this as you would other form input fields such as text boxes.
I have tried doing things like...
var file = document.getElementById('settings').value;
if(file.length > 0 == false){
//give error messsage here
I know that there should be an easy fix for this but I cant quite figure it out.
Thanks
I don't see why this would not work - as long as you give the input an id:
<input type="file" name="settings" id="settings">
<input type="file" name="field_name" onchange="validate_file_format('field_name','allowed file format as comma separeated')"/>
Ex:
<input type="file" name="sitemap_doc" onchange="validate_file_format('sitemap_doc','doc,pdf')"/>
JS Code:
======
function validate_file_format(field_name, allowed_ext){
obj1=document.req_form;
var temp_field= 'obj1.'+field_name+'.value';
field_value=eval(temp_field);
if(field_value!=""){
var file_ext= (field_value.substring((field_value.lastIndexOf('.')+1)).toLowerCase());
ext=allowed_ext.split(',');
var allow=0;
for ( var i=0; i < ext.length; i++) {
if(ext[i]==file_ext){
allow=1;
}
}
if(!allow){
alert('Invalid File format. Please upload file in '+allowed_ext+' format');
return false;
}
}
return false;
}
What about just doing:
<input type="file" name="settings" id="settings">
You need to give the code an id attribute with the value "settings". You have a strange if construction.
if(file.length <= 0) { //error message
}

Categories

Resources