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');
}
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 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;
}
I have a feedback form in my website. Its very basic and only having a text area to put user feedback and submit.
now i am planing to add one option for attaching a picture along with feedback. Adding another text field easy but
i can't figure out how can i add a file into the JavaScript. Please suggest the required changes to add a file into the below script
function upload() {
var feedback = _("feedback").value;
var status = _("status");
if (feedback == "") {
status.innerHTML = "Empty";
} else {
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "feedback.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText != "ok") {
status.innerHTML = ajax.responseText;
} else {
window.location = "thanks.php";
}
}
}
ajax.send("feedback=" + feedback);
}
}
<form id="form1" enctype="multipart/form-data" onsubmit="return false;">
<input id="feedback" type="text">
<button id="submit" onclick="upload()">Submit Details</button>
<span id="status"></span>
</form>
Here you are:
var x = document.createElement("input");
x.setAttribute("type", "file");
document.querySelector("#form1").appendChild(x);
Hope this help.
Unless you're trying to upload the file using ajax, just submit the form to feedback.php.
<form enctype="multipart/form-data" action="feedback.php" method="post">
<input id="image-file" type="file" />
</form>
If you want to upload the image in the background (e.g. without submitting the whole form) you'll need to use Flash since JavaScript alone can't do this.
jQuery Ajax File Upload
Ajax using file upload
jquery easy example look at first answer
Okay.. so two things you will have t change:
Remove that header ('application/x-www-form-urlencoded') and add 'multipart/form-data' header instead. files can not be sent as urlencoded.
Secondly, in ajax request, instead of sending feedback as string, you need to send FormData object, which supports file upload over ajax:
var myForm = $("#form1")[0];
var formData = new FormData(myForm);
ajax.send(formData);
Update:
Forgot to mention: Of course the third thing you will need is to add to your form!
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.
I was using this code fine on bothe IE9 and Firefox but now it works only on Firefox and it just doesn't execute Java validation part on IE9. Any idea what I may need to do to make it work on both type of browserss? Thanks
<?php
if(isset($_POST['submit'])) {
$first_name=$_POST['fname'];
echo 'Entered First Name = '.$first_name;
}
?>
<html>
<form method="post" enctype="multipart/form-data" action="">
<label for="fname"> First Name: </label> <input type="text" name="fname" /> <br /><br />
<label for="file"> Select File: </label> <input type="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
</script>
</html>
The fact that the files array does not exist is not due to a code error. Internet Explorer 9 and below do not support the HTML5 File API, so you will have to use a workaround such as uploading with a Java applet or Adobe Flash.
Combined with what Alex W said, your code also needs some tweaking. getElementsByName requires a name attribute from where you are trying to select. It returns a NodeList of elements with the name given in the function. .
Change your input to have a name attribute, then you won't even need that function:
<input type="file" name="file" />
id works just fine. See below.
I stand corrected by my own research. All the above is true about getElementsByName, however to retrieve the File object, you have to call it from an array returned by selecting a file input form type. As such, document.getElementById('file').files[0] should work. So will the method below:
window.onload = (function () {
document.forms[0].addEventListener('submit', function (evt) {
//this works
var file = document.forms[0].file.files[0];
//as does this
file = document.getElementById('file').files[0];
if (file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
});
jsFiddle
Even after all is said and done, it still will not work in browsers that do not support the HTML5 File API (looking at you IE).
Edit
Whoa, whoa, whoa hold the reigns? I just read that the id attribute was slated to replace the name attribute once IE6 gets nuked. Apparently this is old news1 2 3.
So I did some testing and it turns out id works just fine when calling the element the same way:
var file = document.forms[0].file;
Prove it? Ok
Looks like you have a script error.
The files property does not seems to be supported in IE9
document.forms[0].addEventListener('submit', function( evt ) {
var f = document.getElementById('file');
var file = f.files ? f.files[0] : f;
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
Demo: Fiddle