save javascript output as textfile - javascript

this is my xml file:-
<child_2 entity_id="2" value="Root" parent_id="1">
<child_4 entity_id="4" value="Activities" parent_id="2">
<child_10066 entity_id="10066" value="Physical1" parent_id="4">
<child_10067 entity_id="10067" value="Cricket" parent_id="10066">
<child_10068 entity_id="10068" value="One Day" parent_id="10067"/>
</child_10067>
</child_10066>
<child_10069 entity_id="10069" value="Test2" parent_id="4"/>
<child_10070 entity_id="10070" value="Test3" parent_id="4"/>
<child_10071 entity_id="10071" value="Test4" parent_id="4"/>
<child_10072 entity_id="10072" value="Test5" parent_id="4"/>
<child_5 entity_id="5" value="Physical" parent_id="4"/>
</child_4>
</child_2>
this is my javscript:-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var xml;
$.get(
"region.xml",
function(data)
{ xml=data; },
"html"
);
function get_list(){
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find('[entity_id="'+$('#select').val()+'"]');
$nodes = $title.find('*');
var result='';
$nodes.each(function(){
result += $(this).attr('entity_id');
result += ',';
});
$("#result").html(result);
}
</script>
<input type="text" id="select">
<input type="button" name="button" value="Search" onclick="get_list()" >
<div id="result">
</div>
here i am try to get all the xml attribute value i am success on them now i want to save this output as a textfile
how its possible
please help me out with this...
thanks

One HTML5 way of doing it:
window.URL = window.URL || window.webkitURL;
function download(/*string*/dataToDownload, /*string*/filename) {
var a = document.createElement('a');
var blob = new Blob(dataToDownload, {'type':'application\/octet-stream'});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.click();
};
You can also use Downloadify library, that uses flash to trigger the download and allow the user to name the file.
Or the most common and safe way is to send the data to php and return it with the correct headers that will trigger the download and also allow the user to name the file

Have a look on
File System API of HTML5
File Writer API link

Writing to a file on client side is not only quite complicated (use ActiveX Scripting.FileSystemObject), but is also a bad practice due to security reasons.

If you want a solution that works cross browser, it's better to post the data to server, to a PHP file for example. This php file can then "offer" the file to download.
See this question to get started: How to force file download with PHP.

Related

generate and make downloadable a doc file with some data in angularjs

I want to take input values from user like name, address, phone. After entering values I want to generate a doc (ms word doc file), make it available to be downloaded locally on click on button using angularjs. How can I achieve this?
Is it possible at client side or it should be from server side?
<input type='text' ng-model='user.username'/>
<input type='number' ng-model='user.phone'/>
<a href='someX.doc' download>download</a>
in my controller, I want to generate doc file, download it on click of link (download).
This will work
In your HTML add the following Line
<a download='someX.doc' ng-click="downloadMyDoc()" ng-href="{{ url }}" style="cursor: pointer">Download</a>
In your angular file add the following
var app=angular.module("myApp",[]);
app.config(['$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}]);
app.controller("homeCtrl",function($scope){
$scope.user={};
$scope.downloadMyDoc=function(){
alert("a");
var user=$scope.user;
var content = 'Username: '+user.username+'phone: '+user.phone;
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
}
});

Open file browser, select XML, parse fields using HTML/JQuery/Javascript

I'm able to launch a file-browser using an HTML Form + JQuery but am having a hard time getting past this point. New to HTML, JQuery, JS.
Essentially, I have a series of existing, empty fields on our page that, after selecting an XML from the file-browser, need to wind up populated with information, parsed from the XML.
Just looking for more open, general direction and resources, haven't been able to find much on the subject. Thanks!
Here is an example using an input type="file" element to read a selected File using XMLHttpRequest to get an XML DOM document to then populate the form elements with the data found in the XML:
function loadData(fileInput) {
var file = fileInput.files[0];
var fileURL = URL.createObjectURL(file);
var req = new XMLHttpRequest();
req.open('GET', fileURL);
req.onload = function() {
URL.revokeObjectURL(fileURL);
populateData(fileInput.form, this.responseXML);
};
req.onerror = function() {
URL.revokeObjectURL(fileURL);
console.log('Error loading XML file.');
};
req.send();
}
function populateData(form, xmlDoc) {
var root = xmlDoc.documentElement;
for (var i = 0, l = form.elements.length; i < l; i++) {
var input = form.elements[i];
if (input.name) {
var xmlElement = root.querySelector(input.name);
if (xmlElement) {
input.value = xmlElement.textContent;
}
}
}
}
<form>
<label>Select XML file to load data from:<input type="file" onchange="loadData(this);"></label>
<br>
<label>foo data
<input type="text" name="foo"></label>
<br>
<label>bar data
<input type="text" name="bar"></label>
</form>
This assumes the XML document selected is a simple XML document with a root element of any name and child elements where the element name matches the input name in the HTML form, for instance
<data>
<foo>foo data</foo>
<bar>bar data</bar>
</data>
First, You should convert xml file to JSON. There are a lot of ways to do this. You can find open source suggestions, just google it.
For example: https://code.google.com/p/x2js/.
When JSON will be got you can easy paste it into necessary fields.

Image size validation

is it possible to validate file image size with jquery class orjavascript ?
Can i do that ? I made some research but did not reach anything
Thank you
If you want to check image file being uploaded on client side, check HTML5 File API. Here are some samples at:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can get file size, find it's type and access binary content.
I was using File API to read EXIF headers from image without uploading image to server.
Here is a source code:
https://gist.github.com/980275/85da4a96a3bb23bae97c3eb7ca777acdea7ed791
Try this:
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="Size()" />
Script:
function Size() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').fileSize;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}

Downloading Javascript File from Website using Python

I am trying to use python to download the results from the following website:
http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY
I was attempting to use mechanize before I realized that the Download File is written in javascript which mechanize does not support. My code so far opens the web page as shown below. I am stuck on how to access the Download link on the web page in order to save the data onto my machine.
import urllib2
def downloadFile():
url = 'http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY'
t = urllib2.urlopen(url)
s = t.read()
print s
The results that are printed are
<html>
<head></head>
<body>
<form name="apiForm" method="POST">
<input type="hidden" name="rowids">
<input type="hidden" name="annot">
<script type="text/javascript">
document.apiForm.rowids.value="4791928,3403495,...."; //There are really about 500 values
document.apiForm.annot.value="48";
document.apiForm.action = "chartReport.jsp";
document.apiForm.submit();
</script>
</form>
</body>
</html>
Does anybody know how I can select and move to the Download File page and save that file to my computer?
After some more research on that link, I came up with this. You can definitely use mechanize to do it.
import mechanize
def getJSVariableValue(content, variable):
value_start_index = content.find(variable)
value_start_index = content.find('"', value_start_index) + 1
value_end_index = content.find('"', value_start_index)
value = content[value_start_index:value_end_index]
return value
def getChartReport(url):
br = mechanize.Browser()
resp = br.open(url)
content = resp.read()
br.select_form(name = 'apiForm')
br.form.set_all_readonly(False)
br.form['rowids'] = getJSVariableValue(content, 'document.apiForm.rowids.value')
br.form['annot'] = getJSVariableValue(content, 'document.apiForm.annot.value')
br.form.action = 'http://david.abcc.ncifcrf.gov/' + getJSVariableValue(content, 'document.apiForm.action')
print br.form['rowids']
print br.form['annot']
br.submit()
resp = br.follow_link(text_regex=r'Download File')
content = resp.read()
f = open('output.txt', 'w')
f.write(content)
url = 'http://david.abcc.ncifcrf.gov/api.jsp?type=GENBANK_ACCESSION&ids=CP000010,CP000125,CP000124,CP000124,CP000124,CP000124&tool=chartReport&annot=KEGG_PATHWAY'
chart_output = getChartReport(url)

Use jQuery to get the file input's selected filename without the path

I used this:
$('input[type=file]').val()
to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.
How can I just get the file name (filename.doc)?
var filename = $('input[type=file]').val().split('\\').pop();
or you could just do (because it's always C:\fakepath that is added for security reasons):
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):
var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()...
var file = path.split('\\').pop();
jsFiddle.
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
jsFiddle.
...or lastIndexOf()...
var file = path.substr(path.lastIndexOf('\\') + 1);
jsFiddle.
Here is how I do it, it works pretty well.
In your HTML do:
<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
Then in your js file create a simple function:
function fileSelect(id, e){
console.log(e.target.files[0].name);
}
If you're doing multiple files, you should also be able to get the list by looping over this:
e.target.files[0].name
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
How about something like this?
var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers
var fileUpload = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0);
var files = fileUpload.files;
var mediafilename = "";
for (var i = 0; i < files.length; i++) {
mediafilename = files[i].name;
}
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Categories