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
Related
I have a form where I have submitted the text from the user input but I dont know how to show the text to a different div in a another page in javascript. can anyone help me solve this issue? thanks for the help.
here is my script:
<input onclick="addTheEvent(); return false;" type="submit" value="Add to list" class="btn btn-primary" />
<script>
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candId');
var getCandId = document.getElementById("candId");
var displayCandId = getCandId.options[getCandId.selectedIndex].value;
function addTheEvent() {
addToTheContent.innerHTML = "name = " +
displayCandId + " at " + scheduleEvent.value;
}
</script>
Another page: (I want to add the value to show in my content div that is in another page)
<pre id="content" style="white-space: pre-wrap;"></pre>
You can use a single page application (SPA).
A single-page application is an app that works inside a browser and does not require page reloading during use.
But the SPA is quite a massive theme. It's required for knowledge of the usage browser history, ajax , etc. So you should try to use variant #2
You can use local localStorage of the browser where you can save your data
localStorage.setItem("key","value") //set value into local storage
localStorage.getItem("key") // get value
The "key" is an any string
On another page use
document.addEventListener("DOMContentLoaded", function(event) {
const dataFromLocalStorage = localStorage.getItem('key');
document.querySelector("#content").innerHTML = dataFromLocalStorage; })
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 the following code for multiple file input
<form action="" enctype = "multipart/form-data" method="post" name="login">
<input type = "file" name = "photo[]" id = "files" multiple onchange = "handleFileSelect(this.files)"/><br/>
<div id="selectedFiles"></div>
<input type="submit" value="Sign In">
</form>
The javascript equivalent function is.
selDiv = document.querySelector("#selectedFiles");
function handleFileSelect(e) {
if(!this.files) return;
selDiv.innerHTML = "";
var files = e;
for(var i=0; i<files.length; i++) {
var f = files[i];
selDiv.innerHTML += f.name + "<br/>";
}
}
What I am getting is upon uploading the second file. The FileList gets overwritten and instead of having 2 files, second file is present in the FileList. Here FileList is passed by this.files.
Also upon passing to the server only second image is passed. I have googled throughly but could not find answer. I would appreciate if anyone could help.
...multiple file input ... The FileList gets overwritten...
Actually that's how the HTML file input with the multiple attribute works—the user must select all the files they want to upload at once, using shift or control click. If the user operates the same file input upload process a second time anything selected prior is discarded and only the most recent selections remain in the FileList.
But isn't there any way for the user upload file multiple times.
To let your site users use an HTML file input element multiple times and keep all the previous selections, you'll need to write to hidden form elements the file (base64 data) received each time the file element is used.
For example:
<form action="process.php" method="post" name="uploadform" enctype="multipart/form-data">
// other form elements if needed
<input type="submit">
</form>
<!-- outside the form, you don't want to upload this one -->
<input type="file" id="upfiles" name="upfiles">
<script>
document.getElementById('upfiles').addEventListener('change', handle_files, false);
function handle_files(evt) {
var ff = document.forms['uploadform'];
var files = evt.target.files;
for ( var i = 0, file; file = files[i]; i++ ) {
var reader = new FileReader();
reader.onload = (function(file) {
return function (ufile) {
var upp = document.createElement('input');
upp['type'] = 'hidden';
upp['name'] = +new Date + '_upfile_' + file.name.replace(/(\[|\]|&|~|!|\(|\)|#|\|\/)/ig, '');
upp.value = ufile.target.result;
ff.appendChild(upp);
}
}(file));
reader.readAsDataURL(file);
}
}
</script>
Next, you need to write a script to run on the server to process the hidden base64 fields. If using PHP you can:
<?php
$path = 'path/to/file/directory/';
// this is either:
// - the absolute path, which is from server root
// to the files directory, or
// - the relative path, which is from the directory
// the PHP script is in to the files directory
foreach ( $_POST as $key => $value ) { // loop over posted form vars
if ( strpos($key, '_upfile_') ) { // find the file upload vars
$value = str_replace(' ', '+', $value); // url encode
file_put_contents($path.$key, base64_decode($value));
// convert data to file in files directory with upload name ($key)
}
}
?>
I ran into the same problem. Thanks for the question and answer. I managed to add several files by adding to the DOM input type file and delegating the click to the detached element :
<form method="POST" enctype="multipart/form-data" action="/echo/html">
<button class="add">
Add File
</button>
<ul class="list">
</ul>
<button>
Send Form
</button>
</form>
With the javascript :
$('form button.add').click(function(e) {
e.preventDefault();
var nb_attachments = $('form input').length;
var $input = $('<input type="file" name=attachment-' + nb_attachments + '>');
$input.on('change', function(evt) {
var f = evt.target.files[0];
$('form').append($(this));
$('ul.list').append('<li class="item">'+f.name+'('+f.size+')</li>');
});
$input.hide();
$input.trigger('click');
});
It is working with Edge, Chrome 50 and firefox 45, but I don't know the compatibility with older versions or other browsers.
See the this fiddle.
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.