edit txt file with javascript or html5 - javascript

Please I need help to edit a txt file in client side, I can't find a good method. I need update the data automatic, without confirmation, like it:
<button onclick="updatefile()">Update</button>
<script>
functiom updatefile(){
var file = "d:\test.txt"
var data = //here any function for load all data from file
...
...
data .= " new data to add";
//here any function for save data in test.txt
.....
}
</script>
Please help me.

You cannot do this in that manner using JS. What you CAN do though is to download it on the client, without having the server intervene by using data urls.
Setting the name of said downloaded file is not cross browser compatible unfortunately...
HTML
<textarea id="text" placeholder="Type something here and click save"></textarea>
<br>
<a id="save" href="">Save</a>
Javascript
// This defines the data type of our data. application/octet-stream
// makes the browser download the data. Other properties can be added
// while separated by semicolons. After the coma (,) follows the data
var prefix = 'data:application/octet-stream;charset=utf-8;base64,';
$('#text').on('keyup', function(){
if($(this).val()){
// Set the URL by appending the base64 form of your text. Keep newlines in mind
$('#save').attr('href', prefix + btoa($(this).val().replace(/\n/g, '\r\n')));
// For browsers that support it, you can even set the filename of the
// generated 'download'
$('#save').attr('download', 'text.txt');
}else{
$('#save').removeAttr('href');
$('#save').removeAttr('download');
}
});

Related

How to store HTML user input data into excel using javascript

I need to create HTML page with JavaScript which can store user information into excel directly. Information can contain user input fields like:
First Name (Datatype: Text)
Last Name (Data Type: Text)
I have tried below code for storing values into CSV but I don't know how to store value in excel sheet.
<hrml>
<head>
<script language="javascript">
function WriteToFile(passForm) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fileLoc = "D:\\sample.csv";
var file = fso.OpenTextFile(fileLoc, 8, true,0);
file.writeline(passForm.FirstName.value + ',' +
passForm.LastName.value);
file.Close();
alert('File created successfully at location: ' + fileLoc);
}
</script>
</head>
<body>
<p>create a csv file with following details -</p>
<form>
Type your first name: <input type="text" name="FirstName" size="20">
Type your last name: <input type="text" name="LastName" size="20">
<input type="button" value="submit" onclick="WriteToFile(this.form)">
</form>
</body>
</html>
Kindly help me for this "How to write HTML input data into Excel using JavaScript"
Thank you so much in advance.
you can create an automation object (in windows) using ActiveXObject() in your javascript code. example:
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
// a text is stored in the first cell
ExcelSheet.ActiveSheet.Cells(1,1).Value = "Texto1";
// the sheet is saved
ExcelSheet.SaveAs("D:\\TEST.XLS");
// close Excel with the Quit() method of the Application object
ExcelSheet.Application.Quit();
You can generate a semicolon separated var with your data and use the window.open function, here is an example:
var data = '';
data += $('#Name').val() + ';'
data += $('#EmployeeID').val();
data += '\r\n';
window.open( "data:application/vnd.ms-excel;charset=utf-8," + encodeURIComponent(data));
You can also generate a formatted html instead a semicolon separated text.
This one uses ActiveX object to write to files on your PC.
It will work only on IE. This is forbidden in browsers by default.
Here's the "normal" use case and how you would be able to complete this with all browsers:
Get form's data (JavaScript)
Make an AJAX request to the server with the data (JavaScript)
The server should have some
logic to get the data and write it to a file (Excel file) (JavaScript, PHP, Java,
C#, 1000s more....)
If you want it to work everywhere, you should put some efforts to create some server too. You may start the server on your local machine so you'll have files saved locally

check uploaded file format on client side

I am creating a web portal where end user will upload a csv file and I will do some manipulation on that file on the server side (python). There is some latency and lag on the server side so I dont want to send the message from server to client regarding the bad format of uploaded file. Is there any way to do heavy lifting on client side may be using js or jquery to check if the uploaded file is "comma" separated or not etc etc?
I know we can do "accept=.csv" in the html so that file extension has csv format but how to do with contents to be sure.
Accessing local files from Javascript is only possible by using the File API (https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) - by using this you might be able to check the content whether it matches your expectations or not.
Here's some bits of code I used to display a preview image clientside when a file is selected. You should be able to use this as a starting point to do something else with the file data. Determining whether its csv is up to you.
Obvious caveat:
You still have to check server side. Anyone can modify your clientside javascript to pretend a bad file is good.
Another caveat:
I'm pretty sure that you can have escaped comma characters in a valid csv file. I think the escape character might be different across some implementations too...
// Fired when the user chooses a file in the OS dialog box
// They will have clicked <input id="fileId" type="file">
document.getElementById('fileId').onchange = function (evt) {
if(!evt.target.files || evt.target.files.length === 0){
console.log('No files selected');
return;
}
var uploadTitle = evt2.target.files[0].name;
var uploadSize = evt2.target.files[0].size;
var uploadType = evt2.target.files[0].type;
// To manipulate the file you set a callback for the whole contents:
var FR = new FileReader();
// I've only used this readAsDataURL which will encode the file like data:image/gif;base64,R0lGODl...
// I'm sure there's a similar call for plaintext
FR.readAsDataURL($('#file')[0].files[0]);
FR.onload = function(evt2){
var evtData = {
filesEvent: evt,
}
var uploadData = evt2.result
console.log(uploadTitle, uploadSize, uploadType, uploadData);
}
}

javascript read from a txt file and inject text into form

I apologize in the advance as I am a total beginner.
I have a pre-existing html form with text fields. I need to have a button that will allow me to upload a txt file (since when trying to look for answer about this, I learned javascript can't just access a file from my PC without me actively uploading it). Then I need the values from this txt file inserted into the text fields (for example, the form has: name, last name, phone etc - and the file will fill out this info).
I am going crazy trying to collect bits and pieces from other people's questions. any help would be greatly appreciated!
it depends on how you would like to have this handled, there are basically two options:
File Upload and page redirect
you could provide a file upload form to upload your textfile, redirect to the same page via form submission, handle the data on serverside (e.g. parse the file and get the values out of it) and let the server inject the values as default properties for the form file which is returned to the browser
XMLHttpRequest File Upload
in modern browsers, the native xhr object supports an upload property, so you could send the file via that upload property. it has to be sent to a serverside script that parses the file and returns the values in a fitting format, e.g. json (which would look like this: {'name':'somename', 'lastName':'someothername'}). then you have to register an eventlistener on completion of this upload (e.g. onload) and set these values on javascript side.
check this out for XMLHttpRequest upload (better solution in my opinion): https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
edit:
well, the easiest solution would be just to provide a textfield and paste the content of the file into this field, hit a button and the content is parsed. then you wouldn't rely on network traffic or even a serverside handling, but could do everything with javascript, e.g. like this:
dom:
<textarea id="tf"></textarea>
<button id="parse">fill form!</button>
js:
var tf = document.getElementById("tf");
document.getElementById("parse").addEventListener("click", function(){
var formData = JSON.parse(tf.value);
//if your textfile is in json format, the formData object now has all values
});
edit: from the link i posted in the comments:
<!-- The HTML -->
<input id="the-file" name="file" type="file">
<button id="sendfile">send</button>
and
document.getElementById('sendfile').addEventListener("click", function(){
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload/path', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var values = JSON.parse(xhr.responseText);
//these are your input elements you want to fill!
formNameInput.setAttribute('value', values.name);
formFirstNameInput.setAttribute('value', values.firstName);
}
}
xhr.send(formData);
});
as already said, your serverside has to parse the file and respond with json

Read and display the text file contents upon click of button using Javascript

On click of a button called result, I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using Javascript function and display the test.txt file contents in a HTML text area.
I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?
An Ajax request to a local file will fail for security reasons.
Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!
To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("result");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
}
JS Fiddle
Using $.ajax() function: http://api.jquery.com/jQuery.ajax/
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
As You've mentionned HTML, I assume you want to do this in a browser; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.
We could achieve this by, I should say, creating a virtual file!
Storing the contents of the text file into a Javascript string variable. However, one should consider all new lines and other special symbols\characters and etc.!
We than can markup a script tag in our HTML to load that *.js Javascript like this:
<script src="my_virtual_file.js"></script>
The only difference here is that a text file that could contain:
Goodnight moon
Follow the white rabbit
In a Javascript script string variable should look like this:
var my_virtual_file = "Goodnight moon\nFollow the white rabbit";
Later on, you can access this variable and treat it as you wish...
A programming language like Javascript that follows standards like ECMAScript, gives you a wide range of capabilities to treat and convert data from one type into another.
Once you have your Javascript script loaded, you can then access that variable by any button in your HTML by assigning a function call on its onclick attribute like this:
<button onclick="MyVirtualFile()"></button>
And ofcourse, you just add a script tag to your HTML, like this:
<script>
functiion MyVirtualFile(){
alert(my_virtual_file);
};
</script>
... or your may just create and import another Javascript script containing that same function, under your desire.
If you are concerned about how much information you can store into a Javascript string variable, just take a look at this interesting (and old as this one :D) SO thread.
Lets see if this snippet works :):
var my_virtual_file = "Goodnight moon\nFollow the white rabbit"
function MyVirtualFile(){
alert(my_virtual_file);
// Do anything else with your virtual file
};
<!DOCTYPE html>
<html>
<head>
<script src="my_virtual_file.js">
</script>
</head>
<body>
<h1>HTML Javascript virtual file</h1>
<button onclick="MyVirtualFile()">Alert my_virtual_file</button>
</body>
</html>
You can programatically access and dynamically change the contents of your Javascript script, but you should remind that you need to reload your HTML so the browser can load the new contents.
On your filesystem, you can just treat this *.js as a *.txt file, and just change its contents keeping in mind the Javacript.

Validating a pdf file other than its extension in javascript?

I give user the option of uploading a file like this
<form action="#" onsubmit="return Checkfiles(this);">
<center><input type="file" id="filename">
<input type="submit" value="Go!"></center>
</form>
When user uploads the file, I validate the file using the following javascript function
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "pdf" )
{
return true;
}
else
{
alert("Upload pdf files only");
fup.focus();
return false;
}
}
</script>
Evertything is working fine with it.
But I want to validate file by some other means and not just by its extension
I will give reason for doing this. I renamed an image file to image.pdf and now its in pdf format but couldnt be opened.
So I want to validate a pdf file in exact way. Is there any other way to check other than by its extension?
Edit
I want to do validation at server end using jsp page. So what should I do for that?
Thanks in ADVANCE :)
To validate a filetype on javascript, here are some ways:
// Your way: getting the extension and checking it.
// I suggest this way instead of using indexOf:
var ext = fileName.split('.').reverse()[0]
// Splits by '.', reverse the array, and returns the first element
// Another way: checking the type of the file
if ( fup.files[0].type === 'application/pdf' ) {
console.log( 'It is validated!' )
}
Live example: http://jsbin.com/akati3/2 thanks to https://stackoverflow.com/a/4581316/851498
But then, you should really validate this on the server side as others said.
Any kind of javascript validation is only for users comfort. Everything should be validated on serverside too. User can easily disable or modify any javascript code.
Anyway. you can't check file contents in javascript.
In PHP, you can use http://www.php.net/manual/en/function.finfo-file.php to detect file type by it's contents. Most of other languages should have similar functionality.
As far as I know, checking if a pdf actually is a pdf can only be done on server side. You could try and open it with IText or something similar; I bet it throws some sort of exception when you try opening or modifying something else then a PDF.

Categories