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);
}
}
Related
I have a little script for uploading images with PHP and showing a preview picture before click "upload". It uses an input "multiple" for upload multiple files... So done, it works fine, but I have a little problem ...
When I duplicate the input type="file" (and erase Multiple) with two, three or more inputs, PHP processes the uploaded files but JavaScript shows the first picture only ...
How can I show a picture for all the inputs?
This is my script :
index.php
<?php include("file-upload.php"); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<title>PHP 7 Upload Multiple Files Example</title>
<style>
.container {
max-width: 450px;
}
.imgGallery img {
padding: 8px;
max-width: 100px;
}
</style>
</head>
<body>
<div class="container mt-5">
<form action="" method="post" enctype="multipart/form-data" class="mb-3">
<h3 class="text-center mb-5">Upload Multiple Images in PHP 7</h3>
<div class="user-image mb-3 text-center">
<div class="imgGallery">
<!-- Image preview -->
</div>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input" id="chooseFile" multiple>
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
Upload Files
</button>
</form>
<!-- Display response messages -->
<?php if(!empty($response)) {?>
<div class="alert <?php echo $response["status"]; ?>">
<?php echo $response["message"]; ?>
</div>
<?php }?>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script>
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#chooseFile').on('change', function() {
multiImgPreview(this, 'div.imgGallery');
});
});
</script>
</body>
</html>
The #chooseFile CSS selector selects by ID - that's what the # does. IDs must be unique in HTML (obviously, because the whole point of an ID is to uniquely identify something). So to make that select several input elements, you'd be best to use a class instead as the selector.
For example:
$(function() {
// Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('.chooseFile').on('change', function() {
console.log("detected change");
multiImgPreview(this, 'div.imgGallery');
});
});
.imgGallery img {
padding: 8px;
max-width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="custom-file">
<input type="file" name="fileUpload[]" class="custom-file-input chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<div class="imgGallery">
<!-- Image preview -->
</div>
You might find jQuery's documentation about selectors is useful background reading: https://api.jquery.com/category/selectors/
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>
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>
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='';
}
}
}
So I got this script that is supposed to output the file contents of an uploaded file in base64 encoding, the problem is that it also outputs something like data:image/jpeg;base64, at the beginning of the encoded output. What do I need to do so this script just outputs the encoded file contents of the uploaded file and not data:image/jpeg;base64, etc?
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
document.write(imgUrl);
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
change code to
document.write(imgUrl.split(',').pop());
^^^^^^^^^^^^^^^^^
or
var imgUrl = $('#uploadImageValue').val().split(',').pop();
^^^^^^^^^^^^^^^^^