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.
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 have the following code. It can open a file and display it in the browser. But I want to:
- Select many files instead of one;
- Then Filter on these files for a word (username);
- Then print username's line (text file: username xxxx);
- If the word "username" is not found , print - text file: not found
Any idea?
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
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;
}
}
/**
* read text input
*/
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>
I havent tested this, but does the basic idea work? Read the files through a for-loop, and search for your target string. If you get to the end and you dont find it, return your empty message;
function SearchFiles(var target_string, var file_paths){
var fs = require("fs");
my_file_paths.foreach(function(filepath){
var text = fs.readFileSync(filepath);
var pos = text.search(target_string);
if (pos>1) {
return text.substring(pos, pos + target_string.length);
}
}
return "not found"
}
// now to use the function
var my_file_paths; // init this to what you want to search through
var target_username; // init this as well
var found_username = SearchFiles(target_username, my_file_paths);
DisplayContents("text file: " + found_username);
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>
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">
I'm parsing a CSV file into arrays and using jquery.csv to do the grunt work. My script reads:
<script>
$(document).ready(function() {
// The event listener for the file upload
document.getElementById('txtFileUpload').addEventListener('change', upload, false);
// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}
return isCompatible;
}
// Method that reads and processes the selected file
function upload(evt) {
if (!browserSupportFileUpload()) {
alert('The File APIs are not fully supported in this browser!');
} else {
var data = null;
var file = evt.target.files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event) {
var csvData = event.target.result;
data = $.csv.toArrays(csvData);
if (data && data.length > 0) {
alert('Imported -' + data.length + '- rows successfully!');
} else {
alert('No data to import!');
}
};
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
}
});
My console reads that there is an "Uncaught TypeError: Cannot read property 'toArrays' of undefined". Also in the head section, I imported the library using <script src="jquery.csv-0.71.js"></script>, the JS file residing in the same folder. Any ideas why this error is occurring? Have I imported the library incorrectly, do I need to initialize something? Thanks!
Make sure you're importing jquery.csv-0.71.js after importing jQuery and that your script is running after both.
<script src="jquery.js"></script>
<script src="jquery-csv.js"></script>
<script>/* Your script */</script>