Multi File upload "files[]" javascript validation - javascript

On my site I have multi file upload form with fields:
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
<input name="files[]" type="file" id="files" size="30" />
and I want to validate this fields with javascript code, I know how to get value for some simple fields with javascript but I don`t know how to get values from this fields with names "files[]", how javascript see this fields, array or...?
How to apply validation of size and file type using javascript

<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Name-Type-Size</button>
<script>
function myFunction() {
var input, file;
if (!window.FileReader) {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
var input=document.getElementsByName('files[]');
for(var i=0;i<input.length;i++){
var file = input[i].files[0];
bodyAppend("p", "File " + file.name + " is " + formatBytes(file.size) + " in size"+" & type is "+ fileType(file.name));
}
}
//function to append result to view
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
//function to find size of file in diff UNIT
function formatBytes(bytes,decimals) {
if(bytes == 0) return '0 Byte';
var k = 1000;
var dm = decimals + 1 || 3;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//function to find file type
function fileType(filename){
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
}
</script>
</body>
</html>
Check this now you can put conditions on type of file & size.

// Try this jQuery ;)
$("form").on('change', 'input[type=file]', function() {
var file;
var this = $(this);
if (file = this.files[0])
{
var img = new Image();
img.onload = function () {
// correct
// check alert(img.src)
}
img.onerror = function () {
//error info
};
img.src = _URL.createObjectURL(file);
}
}

<!DOCTYPE html>
<html>
<body>
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<input name="files[]" type="file" id="files[]" size="30" />
<button onclick="myFunction()">Get File Type</button>
<script>
function myFunction() {
var file=document.getElementsByName('files[]');
for(var i=0;i<file.length;i++){
console.log(file[i].value);
}
}
</script>
</body>
</html>
you can get files name like this.

Thanks Bhavik vora But already done with this one
<html>
<head>
<title>client-side image (type/size) upload validation</title>
<meta charset=utf-8>
<style>
</style>
</head>
<body>
<form><fieldset><legend>Image upload</legend>
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
<input type="file" name="file[]" onchange="getImg(this,100,'jpeg|png')">
</fieldset>
</form>
<script>
function getImg(input,max,accepted){
var upImg=new Image(),test,size,msg=input.form;
msg=msg.elements[0].children[0];
return input.files?validate():
(upImg.src=input.value,upImg.onerror=upImg.onload=validate);
"author: b.b. Troy III p.a.e";
function validate(){
test=(input.files?input.files[0]:upImg);
size=(test.size||test.fileSize)/1024;
mime=(test.type||test.mimeType);
mime.match(RegExp(accepted,'i'))?
size>max?(input.form.reset(),msg.innerHTML=max+"KB Exceeded!"):
msg.innerHTML="Upload ready...":
(input.form.reset(),msg.innerHTML=accepted+" file type(s) only!")
}
}
</script>
</body>
</html>

Related

CSV file generation from HTML inputted data

I was trying to pass user inputted data in HTML form to csv file on local drive.
But seems some error in it.
I have tried below code even that is copied from other sources.
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\sample.txt";
var file = OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
</br></br></html>
CSV file is not getting created and cant get any error in HTML.
You were not using the variable fso to call OpenTextFile, you should also keep in mind that IE has permissions to write in the path
This should work for you:
<html>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "C:\\Users\\yourUser\\sample.csv";
var file = fso.OpenTextFile(fileLoc,2,true,0);
file.write("File handling in Javascript");
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
You can also use this solution that works for several browsers:
<html>
<head>
<script language="javascript">
function downloadCSV(form) {
const content = 'Write your csv content here!!';
const mimeType = 'text/csv;encoding:utf-8';
const fileName = 'download.csv';
const a = document.createElement('a');
if (navigator.msSaveBlob) { // IE10
navigator.msSaveBlob(new Blob([content], {
type: mimeType
}), fileName);
} else if (URL && 'download' in a) { //html5 A[download]
a.href = URL.createObjectURL(new Blob([content], {
type: mimeType
}));
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20"><br>
Type your last name: <input type="text" name="LastName" size="20"><br>
<input type="button" value="submit" onclick="downloadCSV(this.form)">
</form>
</body>
</html>

How to display file name with javascript after upload

I want to use a different button to upload files to a form. Therefore, i hide the standard upload file button. However, i do want to display the filename when a user uploads a file.
Using wordpress contact form 7, i already tried putting a JS function on the label, but that doesnt work.
<label for="fileInput" class="custom-file-upload" onclick="displayfilename()">Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<script>
function displayfilename()
$('#fileInput').change(function(){
var filename = $(this).val().split('\\').pop();
});
</script>
The filename should be displayed next to the label.
You can use Event​.target along with triggering the change event.
Please Note: You also have syntax error in your code (missing the {.......} part of the function displayfilename).
$('#fileInput').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
OR: You can also use this object:
$('#fileInput').change(function(){
var filename = $(this)[0].files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
$('#fileInput').change(function(e){
var filename = e.target.files[0].name;
console.log(filename);
});
function displayfilename() {
$('#fileInput').trigger('change');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload" >Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
You can access the file name in this way:
<label for="fileInput" class="custom-file-upload" onclick="displayfilename()">Choose file</label>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<script>
function displayfilename()
$('#fileInput').change(function(e) {
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
</script>
Here's a custom <button> and a custom filename <span>:
$('.choosefile').click(function () {
$('#fileInput').click();
});
$('#fileInput').change(function(e) {
var filename = this.files[0].name;
$('.fileuploadspan').text(filename);
});
input[type=file] {
display: none
}
.choosefile, .fileuploadspan {
font-family: "Comic Sans MS"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fileInput" class="custom-file-upload">Choose file</label>
<button class="choosefile">Browse...</button>
<input id="fileInput" name="fileInput" type="file" />
<span class="fileuploadspan">No file selected</span>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label for="fileInput" class="custom-file-upload">Choose file
<input id="fileInput" name="fileInput" type="file" onchange="uploadPreview(this)" style="display:none"/>
</label><br>
<span class="fileuploadspan">No file selected</span>
</body>
</html>
js
uploadPreview = function (fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var reader = new FileReader();
reader.onload = function (e) {
var filename = file.name;
filename = filename.replace('.jpg', '');
filename = filename.replace('.jpeg', '');
filename = filename.replace('.png', '');
filename = filename.replace('.gif', '');
filename = filename.replace('.bmp', '');
$('.fileuploadspan').text(filename);
return;
};
reader.readAsDataURL(file);
}
}

How do I validate multiple input fields at the same time

I'm trying to validate file type so only JPGs or PNGs can be submitted in my form. I've set it so onChange of the image upload field an alert pops up and the 'upload' button is hidden. However I have 5 fields and if I choose a correct filetype in another box the button is then shown even if the wrong filetype is still selected in another field. How can I clear the input field at the same time as triggering the alert if the filetype is wrong?
I've tried this.value = ""; between changing the class and the alert but I'm not sure of the correct syntax to clear the current box
function validate(fName){
splitName = fName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType != 'jpg' && fileType != 'jpeg' && fileType != 'png'){
document.getElementById("uploadbutton").className = "hide";
alert("You must select a .jpg or .png, file.");
}
else {
document.getElementById("uploadbutton").className = "fwdbutton upload";
}
}
<div id="upload">
<h2>If possible, please could you include photographs of the following:</h2>
<p><label for='uploaded_file1'>Current boiler:</label> <input type="file" name="uploaded_file1" id="uploaded_file1" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p>
<p><label for='uploaded_file2'>Gas meter:</label> <input type="file" name="uploaded_file2" id="uploaded_file2" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p>
<p><label for='uploaded_file3'>Boiler pipe work:</label> <input type="file" name="uploaded_file3" id="uploaded_file3" class="uploadfields" accept="image/png, image/jpg, image/jpeg"onChange="validate(this.value)">X</p>
<p><label for='uploaded_file4'>Outside flue:</label> <input type="file" name="uploaded_file4" id="uploaded_file4" class="uploadfields" accept="image/png, image/jpg, image/jpeg"onChange="validate(this.value)">X</p>
<p><label for='uploaded_file5'>Anything else relevant:</label> <input type="file" name="uploaded_file5" id="uploaded_file5" class="uploadfields" accept="image/png, image/jpg, image/jpeg" onChange="validate(this.value)">X</p><br />
<input class="backbutton showmoved" type="button" value="<< back" /> <input class="fwdbutton upload" id="uploadbutton" type="button" value="upload >>" />
<p><a class="nophotos" id="nophotos">I have no photos >></a></p>
</div>
Many thanks for any advice,
Helen
Please try this.
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
File 1: <input type="file" name="file1" onchange="ValidateSingleInput(this);" /><br />
File 2: <input type="file" name="file2" onchange="ValidateSingleInput(this);" /><br />
File 3: <input type="file" name="file3" onchange="ValidateSingleInput(this);" /><br />
use a counter to see if you have more errors:
var counter= 0;
function validate(fName){
splitName = fName.split(".");
fileType = splitName[1];
fileType = fileType.toLowerCase();
if (fileType != 'jpg' && fileType != 'jpeg' && fileType != 'png'){
alert("You must select a .jpg or .png, file.");
counter = counter + 1;
}
if (counter !=0){
document.getElementById("uploadbutton").className = "hide";
}else{
document.getElementById("uploadbutton").className = "fwdbutton upload";
}
}
each time you run the function it will check if you have an error. This code otherwise is an example and doesn't handle if you fix a previously marked error.
My advice is to redesign the code to check each input once on button click and trigger the alert of the submission. Instead of doing so that is overcomplicating things. So leave the button always visible and run the function on uploadButton click
Hope this will help you. Initially Upload button is hidden when all the valid files are selected you will see upload button and any invalid type will give you alert.
var isValid = [0];
var sumTotal=0;
function validate(fileNo){
var files = event.target.files;
var filetype = files[0].type;
if (filetype == 'image/jpeg' || filetype == 'image/jpeg' || filetype == 'image/png'){
isValid[fileNo]=1;
}else{
alert("You must select a .jpg or .png, file.");
isValid[fileNo]=0;
}
sumTotal = isValid.reduce(function(a, b) { return a + b; }, 0);
if(sumTotal==5){
document.getElementById("uploadbutton").style.display="block";
}else{
document.getElementById("uploadbutton").style.display="none";
}
}
<div id="upload">
<h2>If possible, please could you include photographs of the following:</h2>
<p><label for='uploaded_file1'>Current boiler:</label> <input type="file" name="uploaded_file1" id="uploaded_file1" class="uploadfields" onChange="validate(1)">X</p>
<p><label for='uploaded_file2'>Gas meter:</label> <input type="file" name="uploaded_file2" id="uploaded_file2" class="uploadfields" onChange="validate(2)">X</p>
<p><label for='uploaded_file3'>Boiler pipe work:</label> <input type="file" name="uploaded_file3" id="uploaded_file3" class="uploadfields" onChange="validate(3)">X</p>
<p><label for='uploaded_file4'>Outside flue:</label> <input type="file" name="uploaded_file4" id="uploaded_file4" class="uploadfields" onChange="validate(4)">X</p>
<p><label for='uploaded_file5'>Anything else relevant:</label> <input type="file" name="uploaded_file5" id="uploaded_file5" class="uploadfields" onChange="validate(5)">X</p><br />
<input class="backbutton showmoved" type="button" value="<< back" /> <input class="fwdbutton upload" style="display: none;" id="uploadbutton" type="button" value="upload >>" />
<p><a class="nophotos" id="nophotos">I have no photos >></a></p>
</div>
You can use the following regular expression to check whether the file valid.
/\.(jpe*g|png)$/gi
And then you can use the test() method to check if the file is valid in your if statement.
if(/\.(jpe?g|png)$/gi.test(s)) {
//TODO
}

how to set file name to input value

Below script is working fine .. Its showing file name in alert statement .. But I want filename in input statement. Example if I upload the 1 st file I want file name in id='0' , if it is 2nd one I want file name in id='1'
<body>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input type="file" class="input"/>
<input id="0">
<input id="1">
<input id="2">
<input id="3">
<input id="4">
<script>
var inputArray = document.getElementsByClassName('input');
for(var i = 0; i < inputArray.length; i++){
inputArray[i].addEventListener('change',prepareUpload,false);
};
function prepareUpload(event)
{
var files = event.target.files;
var fileName = files[0].name;
document.getElementById("0").value = fileName;
alert(fileName);
}
</script>
</body>
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<input id="mySelect" onchange="myFunction1()" type="file">
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect");
var fileName = files[x].name;
document.getElementById("0").value = fileName;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>

javascript accept only image not working

In my code I want to accept only image file.otherwise it will not accept and will give alert that its not image file.
I have done below code in jsfiddle:--
jsfiddle link
but the problem is it..It is not giving any message.what am I doing wrong?
https://jsfiddle.net/weufx7dy/2/
You forgot to add id on file element
<input type="file" id="file" name="fileUpload" size="50" />
You had used
var image =document.getElementById("file").value;
but forgot to give id to file control so give that
<input type="file" name="fileUpload" id="file" size="50" />
and try following code in w3schools tryit browser and use onClick event on submit button instead of onSubmit
<!DOCTYPE html>
<html>
<body>
<div align="center">
<form:form modelAttribute="profilePic" method="POST"enctype="multipart/form-data" action="/SpringMvc/addImage">
<input type="file" name="fileUpload" id="file" size="50" />
<input type="submit" value="Add Picture" onClick="Validate();"/>
</form:form>
</div>
<script>
function Validate(){
var image =document.getElementById("file").value;
if(image!=''){
var checkimg = image.toLowerCase();
if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){
alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");
document.getElementById("file").focus();
return false;
}
}
return true;
}
</script>
</body>
</html>
Use this :
userfile.addEventListener('change', checkFileimg, false);
function checkFileimg(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "jpg")) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Please make sure your file is in jpg format.\n\n";
alert(txt);
document.getElementById('userfile').value='';
}
}
}

Categories