I have to make a downloadable CSV file when click on the HTML button. I have created CSV data in my Javascript when click on the button. My question is how to write the data to a CSV file and make it downloadable. I have tried HTML5 download attribute to download the CSV file in client side. But HTML5 download attribute not supported by Internet Explorer. So I need to know how to pass the CSV data to ASPX and make it downloadable. Please advise. Thanks in advance.
I have this code to download a csv from a webpage:
JS function:
function downloadCSV(csv_out) {
var blob = new Blob([csv_out], { type: 'text/csv;charset=utf-8' });
var url = window.URL || window.webkitURL;
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = url.createObjectURL(blob);
link.download = "filename.csv";
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, false);
link.dispatchEvent(event);
}
I am assuming you want to have Javascript only solution.
Then you can do following:
var looongCSVTEXT = ''
document.location ='data:Application/vnd.ms-excel,' +
encodeURIComponent(looongCSVTEXT);
UPDATE:
on your page add
<input type='hidden' id='Hidden' runat='server' />
then in javascript (setting mechanism might be different, its up to you how you set CSV data to hidden control)
$('button').on('click', function(){ $('#Hidden').val(CSVData);});
then read the data from hidden control on the server side, and respond with excel file.
If you do not want to save it to disk first read this
Related
I am trying to upload image on my website to add it to the database as base64 encoded string. The problem is I can not receive the file path to upload it by java. On the front-end I am using HTML and javascript, here is the HTML tag:
<div class="col-xs-6">
<label>passport image </label><input id="image-input" type="file"
placeholder="file">
</div>
in javascript I added:
document.getElementById("image-input").value;
The path of the image that arrives to me is 'C:\fakepath\IMAGE_NAME'.
I need a way to send the photo or it's path to the java code, how can I do this while I am not using jsf nor spring.
Some browsers have a security feature that prevents JavaScript from
knowing your file's local full path. It makes sense - as a client, you
don't want the server to know your local machine's filesystem.
I use the object FileReader on the input onchange event for your input
file type! This example uses the readAsDataURL function and for that
reason you should have an tag. The FileReader object also has
readAsBinaryString to get the binary data, which can later be used to
create the same file on your server
Example:
var input = document.getElementById("inputFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
var img = document.getElementById("yourImgTag");
img.src = event.target.result;
}
try this ! using : replace
var imgpath = document.getElementById("image-input").value;
var newPath = imgpath .replace("C:\\fakepath\\", "")
I am developing a custom application in "ServiceNow" which requires Javascript and HTML coding. So, I have a field say, "description" on my form. How may I save this field's value to a word document on the desktop?
While JavaScript cannot create a file for you to download by itself, ServiceNow does have a way for you to create one. Creating a Word document is impossible without the use of a MID server and some custom Java code, but if any file type will do you can create an Excel file using an export URL. To test this out, I made a UI Action in a developer instance running Helsinki on the Problem table. I made a list view that contains only the field that I wanted to save, and then used the following code in the UI action:
function startDownload() {
window.open("https://dev13274.service-now.com/problem_list.do?EXCEL&sysparm_query=sys_id%3D" +
g_form.getUniqueValue() + "&sysparm_first_row=1&sysparm_view=download");
}
When the UI action is used, it opens a new tab that will close almost immediately and prompt the user to save or open an Excel file that contains the contents of that single field.
If you want to know more about the different ways you can export data from ServiceNow, check their wiki-page on the subject.
You can use the HTML5 FileSystem API to achieve that
window.requestFileSystem(window.PERSISTENT, 1024*1024, function (fs) {
fs.root.getFile('file.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob([description.value], {type: 'text/plain'});
fileWriter.write(blob);
});
});
});
FYI, chrome supports webkitRequestFileSystem.
Alternatively, use a Blob and generate download link
var text = document.getElementById("description").value;
var blob = new Blob([text], {type:'text/plain'});
var fileName = "test.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.href = window.webkitURL.createObjectURL(textFile);
downloadLink.click();
Javascript protects clients against malicious servers who would want to read files on their computer. For that reason, you cannot read or write a file to the client's computer with javascript UNLESS you use some kind of file upload control that implicitely asks for the user's permission.
First of all let me clarify that what I'm trying to do is for locally use only, users will have direct access to the html page.
What I'm trying to do is basically append and save text to an HTML file.
This is what I have.
HTML (index.html)
<div id="receiver"></div>
<button id="insertButton">Insert</button>
JS
$(document).ready( function() {
$('#insertButton').click(function(){
$('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
})
});
What I don't know is how to save the file (index.html) after the appending. Any idea how to do that? Is this even possible with Javascript or jQuery?
You could change your handler to do this:
$(document).ready( function() {
$('#insertButton').click(function(){
$('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
// Save the page's HTML to a file that is automatically downloaded.
// We make a Blob that contains the data to download.
var file = new window.Blob([document.documentElement.innerHTML], { type: "text/html" });
var URL = window.webkitURL || window.URL;
// This is the URL that will download the data.
var downloadUrl = URL.createObjectURL(file);
var a = document.createElement("a");
// This sets the file name.
a.download = "source.htm";
a.href = downloadUrl;
// Actually perform the download.
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
});
You should take a look at the compatibility matrix and documentation of URL over at MDN. Notably URL is not available for IE 9 or earlier. Same for Blob.
If I understand it correctly, you need it on local machine and for temporary usage then you can store it in cookies.
So whenever you load the page, check if cookie available, if yes then load data from cookies or load the fresh data.
You can use this data, unless and until cookies are not cleared.
Hope this helps...
Don't need any javascript. After the html is appended, just press Ctrl+S to save the file locally with modified html.
I am creating a web page that will have many text input boxes structured like the below example.
<input type="text" id="textID" name="textName" placeholder="Enter your text here">
I will have a button at the bottom of the page that I want to grab all the values from each text box, preferably if possible Serialize into XML format and then save locally. If Serializing is not possible, saving to a txt/doc/etc will work. I am using javascript to do that work.
I have figured out how to have my button when clicked save a document of my choosing locally, but I have to use a web url to pull from and this only saves the page source code. That does me no good. I cannot figure out what to put in place of the below save.href. The save.href is forcing the use of the URL which I do not want.
<HTML>
//web page stuff
//Many of these inputs like this one below
<input type="text" id="textID" name="textName" placeholder="Enter your text here">
<script language="javascript" type="text/javascript">
function SaveData()
{
var fileURL = "http://localhost:51088/index.html";
var fileName = "test.txt";
if (!window.ActiveXObject)
{
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE
else if (!!window.ActiveXObject && document.execCommand)
{
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
</script>
</HTML>
This code above is producing a text file that downloads locally to my box but it is only of the page source code for the URL I provided. How can I grab all the values from the text boxes and save that data locally?
I know I can do something like this example below to grab the text box values but how can I then take this value and save it?
var textBoxValue = document.getElementById("textID").value;
And an additional path I ultimately would like to take is to somehow write a C# business layer code that can bind directly to the text boxes on the web page. If not bind, at least pass the values to the C# code. If I can achieve that then I can handle formatting, saving, etc within C#. Is it possible to have an HTML web page, with JavaScript as the UI and C# as the back end?
Is it possible to have an HTML web page, with JavaScript as the UI and C# as the back end?
Yes it is possible, using a website project or even a web application project from visual studio at least.
Additionally, the answer at How to write data to textfile using JavaScript may be what you are looking for to troubleshoot the saving text box values to a text file.
I have managed to figure out how to grab the values from each text box and save them to a text file. Code sample below does it. Now to research how to put this in XML format.
var userInput = document.getElementById("userInputId").value;
var fileURL = 'data:application/notepad;charset=utf-8,' + encodeURIComponent(userInput);
var fileName = "test.txt";
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE
else if (!!window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
I have a text file in my local machine.
And i have a button in jsp page.
On click of the button, i need to get the text file contents.
And the file has n number of contents.
Can anyone give me javascript function to achieve this.
You should specify in your question that you want client side file reading as I see a lot are referring to server side reading.
You should have a look in FileAPI - an HTML 5 Javascript addition that allows JavaScript to read file content via the file input.
I am working on code example for you - but here is a good site you should read
http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html#fbid=4Fhi9T4mEAA
Without FileAPI - you can still use the file input field in form with target="some iframe" - then let the server upload the file and return the text. ( FormData allows uploading files in Ajax but it is not supported in all browsers ).
So File API is your way to go
Here is how you do it with File API
<input type="file"/>
<script>
$(function(){
$("input").change(function(e){
console.log(["file changed",e]);
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(["this is the contents of the file",e.target.result]);
};
reader.readAsText(myFile)
});
}
)
</script>
You can also implement a drag/drop interface (like google gmail has )
$("div").on("dragover",function(e){
e.dataTransfer = e.originalEvent.dataTransfer;
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}).on("drop",function(e){
e.dataTransfer = e.originalEvent.dataTransfer;
e.stopPropagation();
e.preventDefault();
console.log(["selected files", e.dataTransfer.files])});