fetch name of file/image uploaded - javascript

I have a form which has file upload input
<form action="abc.php" method="post">
<input name="fileToUpload" type="file" />
<div id="view"></div>
<button type="submit" value="submit" name="submit">Submit</button>
</form>
I wish to fetch the name of the file/image uploaded on click of this input and display it under <div id="view"></div>, but this needs to be done before the form submission. can anyone please tell how this can be done

Try to update your code to following,
<form action="abc.php" method="post">
<input name="fileToUpload" id="files" type="file" />
<div id="view"></div>
<button type="submit" value="submit" name="submit">Submit</button>
</form>
<script>
var control = document.getElementById("files");
control.addEventListener("change", function(event) {
// When the control has changed, there are new files
var i = 0,
files = control.files,
len = files.length;
for (; i < len; i++) {
document.getElementById('view').innerHTML = files[i].name;
}
}, false);
</script>
I hope this helps.

Try this code, it will surely help
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
Script Code
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);

Related

How to get multiple photo names in js?

I tried the code below to get the names of all the images I selected, but when 'alert' I only got 1 name out of the many names I chose. I want all the names of the photos I have selected to be saved in an array
----------------js code-------
$('input[type=file]')[0].files[0].name;
------------html-------------------
<div class="form-group">
<label for="file">Chọn file Ảnh</label>
<input class="form-control" id="file" type="file" name="image[]" multiple="multiple"/>
<input type="submit" value="upload" />
</div>
var images = $('input[type=file]')[0].files;
let imageNames = [];
if(images && images.length) {
imageNames = images.map(image => image.name);
}
console.log('All Images', imageNames);
You can try above solution...
You are using only first image from the array, that's why you are getting only one/first image every time.
welcome to SO. you may need to update the question/description as its vague. here is a small snippet to print all the attriutes of uploaded files as you requested.
function printFiles() {
let dt = $('input[type=file]')[0].files;
for (let i = 0; i < dt.length; i++) {
console.log('file Name: ' + dt[i].name + ', file size: ' + dt[i].size + ', file type: ' + dt[i].type + ', last Modified: ' + dt[i].lastModified +
', last ModifiedDate: ' + dt[i].lastModifiedDate);
console.log('-----------------------------------------');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="file">Chọn file Ảnh</label>
<input class="form-control" id="file" type="file" name="image[]" multiple="multiple" />
<input type="submit" value="upload" onclick="printFiles()" />
</div>

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
}

Multi File upload "files[]" javascript validation

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>

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='';
}
}
}

how to browse multiple image or file in jquery?

I want to show multiple files or images after browse from system not uploaded on server can we show this using jquery?
I goggled it and find there is way to show and upload on server:
http://www.dropzonejs.com/
But. I only want to show images or file in this there is drag and drop functionality also present can we use this plugin.
But, when I use this plugin in fiddle it show only attached file name not display image why?
Here is fiddle:
http://jsfiddle.net/my50a3uh/1/
<form id="my-awesome-dropzone" action="/target" class="dropzone"></form>
<input type="file" name="file" />
I hope it may be useful for you.It is running well.
Live Working Demo
HTML Code:
<form enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
JS Code
function fileSelect(evt) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = evt.target.files;
var result = '';
var file;
for (var i = 0; file = files[i]; i++) {
// if the file is not an image, continue
if (!file.type.match('image.*')) {
continue;
}
reader = new FileReader();
reader.onload = (function (tFile) {
return function (evt) {
var div = document.createElement('div');
div.innerHTML = '<img style="width: 90px;" src="' + evt.target.result + '" />';
document.getElementById('filesInfo').appendChild(div);
};
}(file));
reader.readAsDataURL(file);
}
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
document.getElementById('filesToUpload').addEventListener('change', fileSelect, false);

Categories