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>
Related
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);
What I would like to have happen is a when a user uploads a CSV from an HTML page that file should save to a local directory that I have provided.
One of two things should happen, if the file already exists it should overwrite, otherwise it should create a new file.
Here is the code that I have:
<!DOCTYPE html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script type="text/javascript">
$(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);
};
}
}
});
</script>
</head>
<body>
<div id="dvImportSegments" class="fileupload ">
<fieldset>
<legend>Upload your CSV File</legend>
<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />
</fieldset>
</div>
<script>
document.getElementById("data").innerHTML;
</script>
</body>
</html>
You need a server (PHP or NodeJS) that exposes this html file ( usually placed in a public folder ) and then serve this html file, you can then do the validation and the storage through the server. You could later on add a database hook, but that depends on your needs and probably the amount of data you'll be uploading.
Has anyone been able to upload files to Dropbox using Javascript SDK for Dropbox (Link to Dropbox javascript SDK) API V2 in Cordova Application? I had a look at the Dropbox-sdk.js file for method to upload files but all the methods require content of the file we want to upload to dropbox More about Upload methods here. How do we provide the content of the files?
The examples from the Javascript Sdk use input type file element to get the files to be uploaded to the Dropbox. But in case of Cordova how to do it? How can we pass the contents of the file?
Below is my code to upload File to Dropbox but when I try to open the uploaded file it show pdf file with no contents.
function uploadFile(tmpStrListStr)
{
var tmpStrList = "";
var uploadSuccess = false;
tmpStrList = tmpStrListStr.substring(0, tmpStrListStr.length-1).split(",");
istrue = true;
for(var i = 0 ; i < tmpStrList.length; i++)
{
var path = cordova.file.externalRootDirectory+'/Test/Logs/'+tmpStrList[i] + '.pdf';
window.resolveLocalFileSystemURL(path, function (fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var ACCESS_TOKEN = localStorage.accessToken;
var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
var fileCommitInfo = {};
fileCommitInfo.contents = reader.result;
fileCommitInfo.path = '/' + fileEntry.name;
fileCommitInfo.mode = { '.tag': 'overwrite' };
fileCommitInfo.autorename = true;
fileCommitInfo.mute = true;
dbx.filesUpload(fileCommitInfo)
.then(function(response) {
alert(response);
})
.catch(function(errr) {
console.log(errr);
});
}
reader.readAsDataURL(file);
});
}, function (e) {
console.log("FileSystem Error");
console.dir(e);
});
}
}
Is there any other way to implement the Dropbox feature(API V2) for Cordova Applications without using Javascript SDK?
Is there anyone in this whole world who can tell me how to upload the files to Dropbox using Javascript SDK V2?
To read the contents of a file used XMLHttpRequest. From the response, created a blob object and then set it to contents parameter of the FilesUpload method.
function UploadNewFile() {
var rawFile = new XMLHttpRequest();
rawFile.responseType = 'arraybuffer';
rawFile.open("GET", "Your file Path Here", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var blobObj = new Blob([rawFile.response],{ type: 'application/pdf',endings: 'native' });
dbx = new Dropbox({accessToken: "Your Access Token"});
if (dbx != null) {
dbx.filesUpload({
path:'/' + "File Name Here"+ '.pdf',
contents: blobObj,
mode: 'overwrite',
mute: true
}).then(function (response) {
var showmsg = "File Upload Complete";
reset();
alertify.alert(showmsg, function (e)
{
if (e)
{
//Code to be executed after your files are successfully uploaded to Dropbox.
}
});
}
}).catch(function (error) {
var showmsg = "Error saving file to your Dropbox!";
reset();
alertify.alert(showmsg);
});
};
}
}
}
rawFile.send(null);
}
Reference:What is blob?
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've written a d3 script that plots some data and in which the path to the input file is hard coded.
I'd like to be able to select the file by browsing on my computer and then passing it to the script.
<body>
<!--locally browse to get the filename-->
<input type="file" id="input">
<script src="http://d3js.org/d3.v3.js"></script>
<script>
// Get the data
d3.tsv("#input", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// then the code that plots etc....
</script>
</html>
1) Create the input select button and register it to a file select handler function:
var input = d3.select("body").append("input")
.attr("type","file")
.on("change", handleFileSelect)
2) The file select handler will register a new function with the fileHandler as input on the onload callback:
// Single file handler
function handleFileSelect() {
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
var f = event.target.files[0]; // FileList object
var reader = new FileReader();
reader.onload = function(event) {
load_d3(event.target.result)
};
// Read in the file as a data URL.
reader.readAsDataURL(f);
}
3) Crete a function with a fileHandler as input, that calls your D3 code (d3.json in this example. You can adapt it for tsv)
function load_d3(fileHandler) {
d3.json(fileHandler, function(error, root) {
//do stuff
};
};
Hope this helps.
Subscribe to input file change event. Then use FileReader to get content of selected file, then parse it using d3.tsv.parse
You can use d3.csvParse to parse the result after reading file. Here's my working code:
<input type="file" id="input" onchange="handleFiles">
<script>
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
var file = fileList[0];
var reader = new FileReader();
reader.onload = function(e) {
// The file's text will be printed here
console.log(e.target.result);
console.log(d3.csvParse(e.target.result));
};
reader.readAsText(file);
}