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.
Related
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
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 have a text file which has 100+ email ids with various domains of my vendor and clients.
Example:
raj#xyz.com,John#gyx.com
I want to place a button which extracts and displays email id with xyz.com and another one which retuns gyx.com likewise. Without PHP I don't have a local server installed.
I have no idea where to start.
This is the code I currently use to read the text file.
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader;
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
Here's the high level approach I would take:
Once the document has loaded up, using jQuery I would grab all of the data output.
var output = $('#main').val()
Then, I would write some logic to parse out the data from the output variable into two different sets (#xyz list and #gyx list). Also, I would format the output too so that it's ready to be called on. Now you have the two data sets that you need, and can call on them when you push your button.
Create an event with jQuery based on the button click state. Depending on the state, the method would select the appropriate list, and then display the output.
So rather than extracting the appropriate data on every button press, you can front load all of it in the initial page load. Since the data won't be changing until you refresh the page again, you should just use the button to switch between which list gets displayed.
It sounds like you want to search your email address list, displaying ids that match a domain or a domains matching an id. First I would take the advice given above and offload your file content into a variable.
This is easy given a comma separated list of email addresses, and here's a plnkr demonstrating the functionality you want (sans the file loading code etc.).
Here's a function to find matches in the address lists based on your criteria.
/**
#emails is a comma separated list of email addresses.
#term is the search term e.g. email id or domain.
#compareById if truthy the function returns email domains with
email id == #text otherwise the function returns email id's
with email domain == #text.
*/
function getEmailMatches(emails, term, compareById) {
let matches = [],
compareIndex = compareById ? 0 : 1,
valueIndex = compareById ? 1 : 0;
emails.split(",").forEach(function (email) {
let terms = email.split("#");
if (terms[compareIndex] == term)
matches.push(terms[valueIndex]);
});
return matches;
}
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.
I have a form stored in a javascript variable below:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload(this);' class='imageuploadform' >" +
"<label> Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label></form>
Now as you can see when the user clicks on the submit button, it submits to the 'startImageUpload' function which is below:
function startImageUpload(imageuploadform){
$(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
$(imageuploadform).find('.imagef1_upload_form').css('visibility','hidden');
sourceImageForm = imageuploadform;
return true;
}
What it does is that when the user clicks on submit, it displays a loading bar and uploads the form.
Now what my question is that I want to perform a simple javascript validation where when the user clicks on the submit button in the form, it will check if the file either a 'png' or 'gif' file type. If it is correct file type, then display the loading bar and upload the form. If the file type is incorrect, then show a n alert stating file type is incorrect but don't show the loading bar and do not upload the form.
Does anyone know how this can be coded. It is so I can use the example from one of your answers to then expand on it and use the javascript to validate on more file types and also file size so it will be very helpful if somebody can please help me.
Thank You
function startImageUpload(imageuploadform){
var form = $(imageuploadform)
, value = form.find('.fileImage').val()
form.find('.imagef1_upload_process').css('visibility','visible')
form.find('.imagef1_upload_form').css('visibility','hidden')
if (!/\.(png|gif)$/.test(value)){
return false
}
return true
}
The HTML specification also evolved to include an accept attribute:
<input type="file" accept="image/png,image/gif" />
(supported in Chrome, Firefox and Opera - IE10, Safari 6 in the near future)
You can check like so...
var validExtensions = ['png', 'gif'],
validExtensionSupplied = $.inArray(
($('.fileImage').val().match(/\.(.*?)]\s*$/) || [])[1],
validExtensions) != -1;
Alternatively, you can validate by MIME type by checking the $('.fileImage').prop('files')[0].type.
Try this:
$("#pic").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'gif': case 'jpg': case 'png':
alert("an image");
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
});
This is my Solution, it is quite Easy and Fast
var accept = $(event.target).attr('accept');
//<input name='fileImage' accept='.png,.jpg,.jpeg' type='file' class='fileImage' />
value = $(event.target).val(), ext = value.substring(value.lastIndexOf('.'));
if(ext && accept.indexOf(ext) == -1){
console.log('No');
}