Consider this:
<input type="file" id="filePicker">
<script>
document.getElementById('filePicker').onchange = function() {
alert('Hi!');
};
</script>
Even if you choose the same file and the filePicker value doesn't change, you'll see the alert box in Firefox. Any solutions?
Use a temporary variable to hold the name of the filename that you can check the next time you select a file:
var filenameTemp = null;
document.getElementById('filePicker').onchange = function(e) {
var filename = e.target.value;
if (filename !== filenameTemp) {
filenameTemp = filename;
console.log('OK');
// other code
} else {
console.log('Not OK')
}
};
DEMO
Run the snippet below. It will say "New File!" when there is a new file for both Chrome and Firefox.
var previousFile = {};
function isSame(oldFile, newFile) {
return oldFile.lastModified === newFile.lastModified &&
oldFile.name === newFile.name &&
oldFile.size === newFile.size &&
oldFile.type === newFile.type;
}
document.getElementById('filePicker').onchange = function () {
var currentFile = this.files[0];
if (isSame(previousFile, currentFile) === false) {
alert('New File!');
previousFile = currentFile;
}
};
<input type="file" id="filePicker">
Related
When i upload multiple images and one of them which is not valid extension and message should be shown File type is not valid and when I upload images one by one it works perfect please help me how can resolve that ? thank u
javascript
$("input[type=file]").on('change', function(){
//Get uploaded file extension
var extension = $(this).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
var validFileExtensions = ['jpeg', 'jpg', 'png'];
//Check file extension in the array.if -1 that means the file extension is not in the list.
if ($.inArray(extension, validFileExtensions) == -1) {
$('#filetype').text("File type is not valid").show();
$('#btnSubmit').prop('disabled', true);
}
});
With the multiple attribute added to the input HTML tag, iterate the files property on the input element in the change event listener.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector("input").addEventListener("change", changeHandler);
});
function changeHandler() {
const validFileExtensions = ['jpeg', 'jpg', 'png'];
// 'this' refers to the 'input' HTML element
// Assigning 'this' to the 'element' variable is not
// necessary but assigned here for code readability.
let element = this;
// Check if the element has a FileList before checking each file
if (element.files && element.files.length) {
for (i = 0; i < element.files.length; i++) {
const file = element.files[i];
const filename = file.name;
const extension = filename.split('.').pop();
if (validFileExtensions.includes(extension)) {
console.log("VALID file -> " + filename);
}
else {
console.log("INVALID file -> " + filename);
}
}
}
}
<input type="file" multiple />
Applying the code above to your jQuery code:
$("input[type=file]").on('change', function() {
//Get uploaded file extension
var extension = $(this).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
var validFileExtensions = ['jpeg', 'jpg', 'png'];
//Check file extension in the array.if -1 that means the file extension is not in the list.
if ($.inArray(extension, validFileExtensions) == -1) {
$('#filetype').text("File type is not valid").show();
$('#btnSubmit').prop('disabled', true);
}
// Check if the element has a FileList before checking each file
if (this.files && this.files.length) {
var message = "";
for (i = 0; i < this.files.length; i++) {
var file = this.files[i];
var filename = file.name;
var extension = filename.split('.').pop();
if (!validFileExtensions.includes(extension)) {
message += filename + " is not a valid file type. ";
}
}
if (message !== "") {
$('#filetype').text(message).show();
$('#btnSubmit').prop('disabled', true);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="fileInput" multiple>
<span id="filetype"></span>
<button type="submit">Upload</button>
const fileInput = document.querySelector('input[type="file"]');
const submitBtn = document.querySelector('button[type="submit"]');
submitBtn.disabled = true;
fileInput.addEventListener('change', () => {
const fileName = fileInput.value;
const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (fileType !== 'jpg' && fileType !== 'jpeg' && fileType !== 'png' && fileType !== 'gif') {
alert('File is not an image');
fileInput.value = '';
submitBtn.disabled = true; // Disable the submit button
} else {
submitBtn.disabled = false; // Enable the submit button
}
});
.fileInput{
text-align:center;
margin-top:10%;
}
<div class="fileInput">
<input type="file" id="fileInput">
<button type="submit">Upload</button>
</div>
I'm trying to debug and find the error, why Change Event is not working on input field. so i have put breakpoint on change event of jquery while debugging but it skip that .i am not able to find why it is not stopping at breakpoint for debugging.
html part which is generated dynamically only a part is shown here.
var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
$("#mainTbl").append(p);
script
<script type="text/javascript">
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
//tried all three trick to envoke change function but not work
//$('input[name=flImage]').change(function () {
$("<input type='file' name='flImage' ID='flImage'/>").change(function () {
//$("input[name=flImage]").on("change", function(){
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
</script>
After show many advice from comment i'm trying like this to access input element
is it ok :div.main main-raised > div#pdfFormInsideL1 > table#mainTbl > tbody >tr>'input[name=flImage]
image given below
var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
$("#mainTbl").append(p);
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
$("input[name=flImage]").on("change", function(){
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainTbl"></div>
have multiple file inputs in form now I have to check for each file input that zip file doesn't contain any invalid files (doc, docx and pdf only allow).
I wrote
<script src="https://code.jquery.com/jquery-2.2.1.js" integrity="sha256-eNcUzO3jsv0XlJLveFEkbB8bA7/CroNpNVk3XpmnwHc=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/js/zip.js"/>
<script type="text/javascript" src="/js/inflate.js"/>
<script type="text/javascript" src="/js/deflate.js"/>
<script type="text/javascript" src="/js/z-worker.js"/>
<script type="text/javascript">
$(document).ready(function () {
if((window.location.href.indexOf("LibraryItemUpload`1&ParentId=7d428470-2234-41c0-85f4-a512d51198c6") > -1) || (window.location.href.indexOf("LibraryItemUpload%601&ParentId=7d428470-2234-41c0-85f4-a512d51198c6") > -1))
{
$("input:file").change(function () {
var regex=new RegExp("^[A-Za-z0-9 ]+$");
var file=this.files[0];
var key = this.value;
var ze = key.split('\\').pop();
var filename = ze.split('.')[0];
var extension=key.split('.').pop().trim().toLowerCase();
if(extension == 'zip')
{
zip.createReader(new zip.BlobReader(file), function(reader) {
// get all entries from the zip
reader.getEntries(function(entries) {
if (entries.length) {
// get first entry content as text
entries[0].getData(new zip.TextWriter(), function(text) {
// text contains the entry data as a String
console.log(text);
// close the zip reader
reader.close(function() {
// onclose callback
});
}, function(current, total) {
// onprogress callback
});
}
});
}, function(error) {
});
}
if (!regex.test(filename)) {
alert('Please do not use special characters in file name please rename file name and upload it again.');
location.reload();
}
else {
return true;
}
});
}
});
</script>
and written code to read file name from zip.js but flow doen't go in zip.createReader function.
please suggest me if another javascript available for read zip file, I just want entries object to read files name.
function readEntries(entries) {
var entryLength = entries.length;
for (i = 0; i < entryLength; i++) {
var entry = entries[i];
var fileName = entry.filename.substring(entry.filename.lastIndexOf("/") + 1); //if inside folder
var ext = fileName.split(".").pop().toLowerCase();
if (ext.toUpperCase() == 'DOC' || ext.toUpperCase() == 'PDF' ||
ext.toUpperCase() == 'DOCX') {
//logic
}
}
}
zip.useWebWorkers = false;//explicitly include (required) zip-workers ['zip.js','zip-fs.js','z-worker.js','inflate.js','deflate.js']
var fileInput = document.getElementById("zipfile");//Input File
fileInput.addEventListener('change', function(event) {
zip.createReader(new zip.BlobReader(fileInput.files[0]), function(zipReader) {
zipReader.getEntries(readEntries);
}, function (error) {
console.log(error);
});
});
I have not tested this piece of code, but I have used similar logic before.
I have this function which generates the File URL using createobjectURL and works when I use the normal input file tag.
I am trying to implement the same using dropzone.js but when I drop the file it starts
showing the upload progress bar although I haven't defined any action.
How can i obtain the URL using dropzone.js?
Javascript
function localFileVideoPlayerInit(win) {
var URL = win.URL || win.webkitURL,
displayMessage = (function displayMessageInit() {
return function displayMessage() {
alert("error");
};
}()),
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
if (canPlay === 'no') {
displayMessage();
}
}
};
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector('input');
if (!URL) {
displayMessage('Your browser is not ' + 'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
}
HTML
<form action="" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
Seems you would have to reference the variable fileURL, and use javascript to dynamically set the action of the form.
I have a question regarding to JavaScript validation. I am validaing the <input type="file"> whenever my scripts runs, it validates but also the action page is called. I want to stop the action page until the validation is complete. Here is my code, any help will be awesome. Regards
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Image Uploading</title>
</head>
<body>
<form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)">
<input type="file" name="file_uploading" id="filename">
<input type="submit" value="Submit" name="uploadfile">
</form>
<form name="view" method="post">
View your uploaded Images
</form>
</body>
</html>
<script type="text/javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext =="GIF" || ext=="gif") {
return true;
} else {
alert("Upload Gif Images only");
return false;
}
}
</script>
var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
alert("File extension not supported!");
}
File Extension Validation through javascript
function ValidateExtension() {
var allowedFiles = [".doc", ".docx", ".pdf"];
var fileUpload = document.getElementById("fileUpload");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "";
return true;
}
onclick event of submit button call this javascript function.
With the help of ID = lblError , print the error message in html section.
You can use the File Api to test for magic number. Maybe take a look at this answer for other ideas about the validation. More reliable than the file extension check.
The return value of the submit handler affects the submission.
onsubmit="return Checkfiles();"
This is basically saying:
form.onsubmit = function () { return Checkfiles(); };
In general, you can use JavaScript some() method for that.
function isImage(icon) {
const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
return ext.some(el => icon.endsWith(el));
}
const fname = "filename.ext";
if (!isImage(fname)) {
console.log("File extension not supported!");
}
You need to return CheckFiles()
Upload bulk data through excel sheet(.csv)
$("form").submit(function(){
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(csv)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only csv file can be uploaded');
return false;
}
});
var _URL = window.URL || window.webkitURL;
$("input[type=file]").change(function(e) {
var file;
if ((file = this.files[0])) {
var img = new Image();
img.onload = function () {
// do to on load
};
img.onerror = function () {
alert("valid format " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension validation.
HTML
<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>
<!-- Image preview -->
<div id="imagePreview"></div>
JavaScript
function fileValidation(){
var fileInput = document.getElementById('file');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if(!allowedExtensions.exec(filePath)){
alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
fileInput.value = '';
return false;
}else{
//Image preview
if (fileInput.files && fileInput.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
};
reader.readAsDataURL(fileInput.files[0]);
}
}
}
fileValidation()
> html
<input type="file" id="userfile" name="userfile" value="" class="form-control userfile" required>
> javascript
$(document).on('change', '.userfile', function (e) {
e.preventDefault();
const thisValue = $(this).val().split('.').pop().toLowerCase();
const userFile = [thisValue];
// Allowing file type
const validFile = ['csv', 'xlsx'];
// const intersection = validFile.filter(element => userFile.includes(element));
// if(intersection == ''){
// $(this).val('');
// alert('Please Select ' + validFile + ' file');
// return false;
// }
// Allowing file type
const allowedExtensions = /(\.csv|\.xlsx)$/i;
if (!allowedExtensions.exec($(this).val())) {
$(this).val('');
alert('Please Select ' + validFile + ' file');
return false;
}
});