upload csv and save it to a local folder Jquery - javascript

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.

Related

Is it possible to load a XLSX file to be converted into an HTML table, without having a user browse for the said XLSX file?

I am currently creating a html page that would load a XLSX file from local directory and then convert it into an HTML table on the same page underneath it, but my current html page requires a user to browse their directory and open said file.
<html>
<input id = "fileUpload" type ="file" >
<input type="button" id="upload" value="Upload" onclick="Upload()"/>
<table id="dvExcel"></table>
<hr>
</html>
<script>
function Upload() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
ProcessExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
ProcessExcel(data);
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
</script>
No - for security reasons it is not allowed to access local files from web pages without user interaction.
This will only work if you deploy a local application or something similar to the users PC.

JAVASCRIPT - Read local file, filter for a word and print word's line

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);

Undefined Function for Imported Library in JavaScript

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>

how to get a filename in HTML and use it in D3.js (javascript)?

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);
}

Trouble uploading binary files using JavaScript FileReader API

New to javascript, having trouble figuring this out, help!
I am trying to use the Javascript FileReader API to read files to upload to a server. So far, it works great for text files.
When I try to upload binary files, such as image/.doc, the files seem to be corrupted, and do not open.
Using dojo on the client side, and java on the server side, with dwr to handle remote method calls. Code :
Using a html file input, so a user can select multiple files to upload at once :
<input type="file" id="fileInput" multiple>
And the javascript code which reads the file content:
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
// fileContent object contains the content of the read file
};
})(this.filesToBeUploaded[i]);
reader.readAsBinaryString(this.filesToBeUploaded[i]);
}
}
The fileContent object will be sent as a parameter to a java method, which will write the file.
public boolean uploadFile(String fileName, String fileContent) {
try {
File file = new File("/home/user/files/" + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileContent.getBytes());
outputStream.close();
} catch (FileNotFoundException ex) {
logger.error("Error uploading files: ", ex);
return false;
} catch (IOException ioe) {
logger.error("Error uploading files: ", ioe);
return false;
}
return true;
}
I have read some answers suggesting the use of xhr and servlets to achieve this.
Is there a way to use FileReader, so that it can read files of any type (text, image, excel etc.) ?
I have tried using reader.readAsBinaryString() and reader.readAsDataUrl() (Decoded the base64 fileContent before writing to a file), but they did not seem to work.
PS :
1. Also tried reader.readAsArrayBuffer(), the resultant ArrayBuffer object shows some byteLength, but no content, and when this is passed to the server, all I see is {}.
This bit of code is intended to work on only newer versions of browsers..
Thanks N.M! So, it looks like ArrayBuffer objects cannot be used directly, and a DataView must be created in order to use them. Below is what worked -
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
var int8View = new Int8Array(fileContent);
// now int8View object has the content of the read file!
};
})(this.filesToBeUploaded[i]);
reader.readAsArrayBuffer(this.filesToBeUploaded[i]);
}
}
Refer N.M 's comments to the question for links to the relevant pages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
example
<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();
alert(imgUrl);
//here ajax
});
});
</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" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>

Categories

Resources