Changing embed src attribute dynamically using file dialog - javascript

I implemented a HTML page which runs locally on a Linux machine (using the most current firefox versions). It is used to embed a plugin which I have programmed.
At the moment, I statically pass a file path, the plugin has to load, that is hard-coded in the HTML file:
<embed id="embed1" type="application/x-bbx" src="/tmp/testfile.bbx"></embed>
The HTML page is generated for all .bbx files. I'm currently trying to figure out how I can avoid the hard-coded path by adding an <input type="file"> element. The aim is to dynamically change the loaded file (specified by src) to avoid the need of generating the HTML page for all .bbx files.
As browsers do not allow access to the file path: how I can change the embed's source according to the loaded file?
For several technical reasons, I would like to avoid using JQuery. Also note, that the page is run solely locally by specific users.
EDIT 1: The plugin is scriptable, i.e. I can invoke functions on and pass parameters to the plugin using JavaScript. Thus, it would suffice to get the whole file path and pass it to the plugin which in turn does the rest internally.
EDIT 2: For clarification: I want to avoid the burden of having the user enter the file path manually, which is why I intended to use <input type="file">

var Target = "/tmp/testfile2.bbx";
var Source = document.getElementById('embed1');
var Clone = Source.cloneNode(true);
Clone.setAttribute('src',Target);
Source.parentNode.replaceChild(Clone,Source);
But history of browser gets no event here... so .back() will work incorrectly.
Thats how I got here today. Hope this helps. And sorry if a was not fluxed to the right moment. ;-)

If I understood right, this should do it!
<script>
var embed1 = document.getElementById('embed1');
embed1.src = 'your path';
</script>

Here is a complete example:
JSFiddle
<input type="text" id="path" name="path" />
<input type="submit" id="submit" value="Change it" onclick="changePath()">
<embed id="embed1" type="application/x-bbx" src="/tmp/testfile.bbx"></embed>
<script>
function changePath() {
var e = document.getElementById('path');
var val = e.value;
var embed1 = document.getElementById('embed1');
embed1.src = val;
}
</script>

Related

On Windows and with React: What can I do to get the full path of a browsed file? [duplicate]

How to get full path of file while selecting file using <input type=‘file’>
<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
but the filePath var contains only name of selected file, not the full path.
I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file.
Is there any other way to get full path of selected file?
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
So don't waste your time.
edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
JSFIDDLE
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value
of the value property depends on the value of the "Include local
directory path when uploading files to a server" security setting for
the security zone used to display the Web page containing the input
object.
The fully qualified filename of the selected file is returned only
when this setting is enabled. When the setting is disabled, Internet
Explorer 8 replaces the local drive and directory path with the string
C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed ); this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
You can't.
Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.
In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.
You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
You can use the following code to get a working local URL for the uploaded file:
<script type="text/javascript">
var path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
</script>
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
but it doesn't contain the whole absolute path, only the relative one. Supported in Firefox also.
you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...
some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)
Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3
One could use the FileReader API for changing the src of an img element.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
This is a working solution for me
const path = (window.URL || window.webkitURL).createObjectURL(file);
It will return a blob URL to locally access the file.
file element has and array call files it contain all necessary stuff you need
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
You can get the full path of the selected file to upload only by IE11 and MS Edge.
var fullPath = Request.Form.Files["myFile"].FileName;
$('input[type=file]').change(function () {
console.log(this.files[0].path);
});
This is the correct form.

Browse "File Upload" not displaying full path through Javascript [duplicate]

How to get full path of file while selecting file using <input type=‘file’>
<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
but the filePath var contains only name of selected file, not the full path.
I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file.
Is there any other way to get full path of selected file?
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
So don't waste your time.
edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
JSFIDDLE
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value
of the value property depends on the value of the "Include local
directory path when uploading files to a server" security setting for
the security zone used to display the Web page containing the input
object.
The fully qualified filename of the selected file is returned only
when this setting is enabled. When the setting is disabled, Internet
Explorer 8 replaces the local drive and directory path with the string
C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed ); this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
You can't.
Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.
In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.
You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
You can use the following code to get a working local URL for the uploaded file:
<script type="text/javascript">
var path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
</script>
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
but it doesn't contain the whole absolute path, only the relative one. Supported in Firefox also.
you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...
some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)
Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3
One could use the FileReader API for changing the src of an img element.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
This is a working solution for me
const path = (window.URL || window.webkitURL).createObjectURL(file);
It will return a blob URL to locally access the file.
file element has and array call files it contain all necessary stuff you need
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
You can get the full path of the selected file to upload only by IE11 and MS Edge.
var fullPath = Request.Form.Files["myFile"].FileName;
$('input[type=file]').change(function () {
console.log(this.files[0].path);
});
This is the correct form.

How to get selected files actual path instead of fake or temporary file path? [duplicate]

How to get full path of file while selecting file using <input type=‘file’>
<input type="file" id="fileUpload">
<script type="text/javascript">
function getFilePath(){
$('input[type=file]').change(function () {
var filePath=$('#fileUpload').val();
});
}
</script>
but the filePath var contains only name of selected file, not the full path.
I searched it on net, but it seems that for security reasons browsers (FF,chrome) just give name of file.
Is there any other way to get full path of selected file?
For security reasons browsers do not allow this, i.e. JavaScript in browser has no access to the File System, however using HTML5 File API, only Firefox provides a mozFullPath property, but if you try to get the value it returns an empty string:
$('input[type=file]').change(function () {
console.log(this.files[0].mozFullPath);
});
https://jsfiddle.net/SCK5A/
So don't waste your time.
edit: If you need the file's path for reading a file you can use the FileReader API instead. Here is a related question on SO: Preview an image before it is uploaded.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
JSFIDDLE
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value
of the value property depends on the value of the "Include local
directory path when uploading files to a server" security setting for
the security zone used to display the Web page containing the input
object.
The fully qualified filename of the selected file is returned only
when this setting is enabled. When the setting is disabled, Internet
Explorer 8 replaces the local drive and directory path with the string
C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed ); this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
You can't.
Security stops you for knowing anything about the filing system of the client computer - it may not even have one! It could be a MAC, a PC, a Tablet or an internet enabled fridge - you don't know, can't know and won't know. And letting you have the full path could give you some information about the client - particularly if it is a network drive for example.
In fact you can get it under particular conditions, but it requires an ActiveX control, and will not work in 99.99% of circumstances.
You can't use it to restore the file to the original location anyway (as you have absolutely no control over where downloads are stored, or even if they are stored) so in practice it is not a lot of use to you anyway.
Did you mean this?
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',tmppath);
});
You can use the following code to get a working local URL for the uploaded file:
<script type="text/javascript">
var path = (window.URL || window.webkitURL).createObjectURL(file);
console.log('path', path);
</script>
One interesting note: although this isn't available in on the web, if you're using JS in Electron then you can do this.
Using the standard HTML5 file input, you'll receive an extra path property on selected files, containing the real file path.
Full docs here: https://github.com/electron/electron/blob/master/docs/api/file-object.md
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
but it doesn't contain the whole absolute path, only the relative one. Supported in Firefox also.
you should never do so... and I think trying it in latest browsers is useless(from what I know)... all latest browsers on the other hand, will not allow this...
some other links that you can go through, to find a workaround like getting the value serverside, but not in clientside(javascript)
Full path from file input using jQuery
How to get the file path from HTML input form in Firefox 3
One could use the FileReader API for changing the src of an img element.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
This is a working solution for me
const path = (window.URL || window.webkitURL).createObjectURL(file);
It will return a blob URL to locally access the file.
file element has and array call files it contain all necessary stuff you need
var file = document.getElementById("upload");
file.addEventListener("change", function() {
for (var i = 0; i < file.files.length; i++) {
console.log(file.files[i].name);
}
}, false);
You can get the full path of the selected file to upload only by IE11 and MS Edge.
var fullPath = Request.Form.Files["myFile"].FileName;
$('input[type=file]').change(function () {
console.log(this.files[0].path);
});
This is the correct form.

SCRIPT5: Access is denied. [duplicate]

We want to reduce the number of steps it takes for a user to upload a file on our website; so we're using jQuery to open and postback files using the below markup (simplified):
<a onclick="$('#uplRegistrationImage').click();">
Change profile picture
</a>
<!-- Hidden to keep the UI clean -->
<asp:FileUpload ID="uplRegistrationImage"
runat="server"
ClientIDMode="static"
Style="display:none"
onchange="$('#btnSubmitImage').click();" />
<asp:Button runat="server"
ID="btnSubmitImage"
ClientIDMode="static"
Style="display:none"
OnClick="btnSubmitImage_OnClick"
UseSubmitBehavior="False" />
This works absolutely fine in Firefox and Chrome; opening the file dialog when the link is clicked and firing the postback when a file is selected.
However in IE9 after the file upload has loaded and a user has selected a file; insteaed of the OnChange working I get a "SCRIPT5 Access is denied" error. I've tried setting an arbitrary timeout, setting intervals to check if a file is given to no avail.
There are a number of other questions relating to this; however none appear to have a decent answer (One said set the file dialog to be transparent and hover behind a button!)
Has anyone else resolved this? Or is it absolutely necessary that I provide a button for IE users?
For security reasons, what you are trying to do is not possible. It seems to be the IE9 will not let you submit a form in this way unless it was an actual mouse click on the File Upload control that triggers it.
For arguments sake, I was able to use your code to do the submit in the change handler, but it worked only when I clicked the Browse button myself. I even set up polling in the $(document).ready method for a variable set by the change handler that indicates a submission should be triggered - this didn't work either.
The solutions to this problem appear to be:
Styling the control in such a way that it sits behind a button. You mentioned this in your question, but the answer provided by Romas here In JavaScript can I make a "click" event fire programmatically for a file input element? does in fact work (I tried in IE9, Chrome v23 and FF v15).
Using a Flash-based approach (GMail does this). I tried out the Uploadify demo and it seems to work quite nicely.
Styling a File Upload:
http://www.quirksmode.org/dom/inputfile.html
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
References:
jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox?
IE9 file input triggering using Javascript
getting access is denied error on IE8
Hey this solution works.
for download we should be using MSBLOB
$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
var fileName = invoiceNumberEntity + ".pdf";
var pdfDownload = document.createElement("a");
document.body.appendChild(pdfDownload);
AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
window.navigator.msSaveBlob(fileBlob, fileName);
} else { // for other browsers
var fileURL = window.URL.createObjectURL(fileBlob);
pdfDownload.href = fileURL;
pdfDownload.download = fileName;
pdfDownload.click();
}
});
};
This solution looks like it might work. You'll have to wrap it in a <form> and get it to post in the jquery change handler, and probably handle it in form_load using the __eventtarget or and iframe or whatever it is that web forms uses, but it allows you to select a file, and by submitting the form, it should send it. I can't test it however, since I don't have an environment set up at home.
http://jsfiddle.net/axpLc/1/
<a onclick="$('#inputFile').click();">
Change profile picture
</a>
<div id='divHide'>
<input id='inputFile' type='file' />
</div>
$('#inputFile').change(function() { alert('ran'); });
#divHide { display:none; }
Well, like SLC stated you should utilize the <Form> tag.
First you should indicate the amount of files; which should be determined by your input fields. The second step will be to stack them into an array.
<input type="file" class="upload" name="fileX[]"/>
Then create a loop; by looping it will automatically be determined based on the input field it's currently on.
$("input[#type=file]:nth(" + n +")")
Then you'll notice that each file chosen; will replace the input name to the file-name. That should be a very, very basic way to submit multiple files through jQuery.
If you'd like a single item:
$("input[#type=file]").change(function(){
doIt(this, fileMax);
});
That should create a Div where the maximum file found; and attaches to the onEvent. The correlating code above would need these also:
var fileMax = 3;
<input type="file" class="upload" name="fileX[]" />
This should navigate the DOM parent tree; then create the fields respectively. That is one way; the other way is the one you see above with SLC. There are quite a few ways to do it; it's just how much of jQuery do you want manipulating it?
Hopefully that helps; sorry if I misunderstood your question.

Save the document generated by javascript

Javascript can manipulate the document the browser is displaying, so the following:
<script>
document.write("<table><tr><td>Hola</td><td>Adios</td></tr></table>");
</script>
Will make the browser display a table just like if it was the original HTML document:
<table>
<tr>
<td>Hola</td>
<td>Adios</td>
</tr>
</table>
Is there a way I can save/serve this document content?
Currently we have some nicely generated reports using Ext-js, what I would like to do is to have the "text/html" version of it ( I mean, something that doesn't require javascript )
So at the end of the page I would add a button : "Save as blaba" and the document should display the text/plain version.
The only way I could think right now is, to write the content into a javascript variable like:
var content = document.toString(); // or something magic like that.
// post it to the server
Then post that value to the server, and have the server present that value.
<%=request.getParameter("content-text")%>
But looks very tricky.
Is there an alternative?
EDIT
Ok, I almost got it. Now I just need the new window to pop up so the option "would you like to save it shows"
This is what I've got so far
<script>
document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function saveAs(){
var sMarkup = document.getElementById('content').innerHTML;
var oNewDoc = document.open('application/vnd.ms-excel');
oNewDoc.write( sMarkup + "<hr>" );
oNewDoc.close();
}
</script>
<input type="button" value="Save as" onClick="saveAs()"/>
The line:
var oNewDoc = document.open('application/vnd.ms-excel');
Should specify the new content type, but it is being ignored.
Unless its being saved client side with File -> Save Page As..., you will have to do exactly what you are proposing, posting $('body').html() to your server and process it as text.
Here's the upgraded version to open the table contents in .xls format.
<head>
<script>
document.write("<table id='targetTable'><tr><td>Hola</td><td>Adios</td></tr><tr><td>eins</td><td>zwei</td></table>");
function saveAsXLS()
{
var xlObj = new ActiveXObject("Excel.Application");
var xlBook = xlObj.Workbooks.Add();
var xlSheet = xlBook.Worksheets(1);
for (var y=0;y<targetTable.rows.length;y++) // targetTable=id of the table
{
for (var x=0;x<targetTable.rows(y).cells.length;x++)
{
xlSheet.Cells(y+1,x+1)=targetTable.rows(y).cells(x).innerText;
}
}
xlObj.Visible=true;
document.write("The table contents are opened in a new Excel sheet.");//Print on webpage
}
</script>
</head>
<body>
<input type="button" value="Open table in Excel!" onclick="saveAsXLS()"/>
</body>
This code is tested in IE6 and is using ActiveXObject control.
The table I've used here is of order 2x2 and the individual contents are mapped respectively into the excel sheet.
Unlike the .doc version, this does not save the file in client's system. It opens the application with the table content and the client has to save it.
Hope this helps in answering ur question. Lemme know if u face any issues.
Peace.
Depending on your browser support requirements, you could use data URIs
Core for proof of concept (tested in Firefox 3.5.3):
document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function extract(){
return document.getElementById('content').innerHTML;
}
function dataURI(s){
return 'data:application/vnd.ms-excel;base64,' + encode64(s);
}
document.write('open');
I pulled base 64 encode/decode from examples online. Careful: the one I grabbed included a URI encode before base 64 encode that messed me up for a while.
You are getting close to the answer I thinks. The problem is that 'document.open(...)' can only take standard mime-types such as 'text/html', 'text/plain' and a few others
And because of that your code should be:
<script>
document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
function saveAs(){
var sMarkup = document.getElementById('content').innerHTML;
var oNewDoc = document.open('text/html');
oNewDoc.write( sMarkup + "<hr>" );
oNewDoc.close();
}
</script>
<input type="button" value="Save as" onClick="saveAs()"/>
Hope this helps.
$(function(){
$('.bbutton').click(function(){
var url='data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html() )
location.href=url
return false
})
})
.table{background:#ddd;border:1px solid #aaa;}
.table thead th{border-bottom:1px solid #bbb;}
.table tr td{background:#eee;border-bottom:1px solid #fff;
border-left:1px solid #ddd;text-align:center;}
.table tr:hover td{background:#fff;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='tableWrap'><table style='width:98%;box-shadow:none;' class='table'>
<thead><th>id</th><th>Name</th><th>Address</th></thead>
<tr><td>1</td><td>Jyoti Telecom Services</td><td>http://www.tsjyoti.com</td></tr>
<tr><td>2</td><td>Recharge</td><td>http://recharge.tsjyoti.com</td></tr>
<tr><td>3</td><td>Bhuri Bharaj</td><td>http://bhuribharaj.tsjyoti.com</td></tr>
</table></div>
<p>Your download's ready as Excel Sheet <a href='#'class='bbutton'>Click Here for download</a></p>
If it's just a report, you could use server-side JavaScript to generate it, and then serve it up with whatever MIME type you need...
I dont think that sending your html to the server is a tricky solution. You just have to remember to give a link to your user to download this file. This can be done using a traditional POST, or even using AJAX. It depends on how you want your users to interact if your page.
Using traditional post, you could put all the html content in the value attribute of an input type hidden in your page, named "html_content" or something like that, and when the user clicks in the button "save" you send your user to another page with a link do the file. You send the html to server, a script creates a file in a filesystem with an unique name, and returns a download link.
Using AJAX, you just need to do an AJAX POST passing this variable, and then your script returns a download link, and you dynamically put it in your html - without reloading your page, like it was "only cliente side".
Either way, you'll return a link to the resource you just created in your filesystem with a html extension. Remember to generate unique names in your server for each generated file to avoid collisions.
Beware though that using innerHTML in IE 6 (I dont know if this is a IE family behavior or just about the 6 version) uppercases all tags and removes quotes from attributes. If you're planning to do some post processing in your html, be careful.
I dont know how jQuery or other JS libraries behaves in such situations. I would suggest using it though, they have plenty of browser compatibility checks to abstract all these hacks we use.
Here's my code to save the generated content[client-side] by the JavaScript to the local C: drive in MSWord[.doc] format.
<script>
document.write("<div id='content'><table><tr><td>Holaa</td><td>Adiosa</td></tr></table></div>");
function saveAs()
{
var wordObj=new ActiveXObject("Word.Application");
var docText;
var obj;
var textToWrite = document.getElementById('content').innerHTML;
if (wordObj != null)
{
wordObj.Visible = false;
wordDoc=wordObj.Documents.Add();
wordObj.Selection.TypeText(textToWrite);
wordDoc.SaveAs("C:\\Eureka.doc");
wordObj.Quit();
document.write("The content has been written to 'C:\\Eureka.doc'");//Print on webpage
}
}
</script>
<body>
<input type="button" value="Save in C:" onclick="saveAs()"/>
</body>
I quickly worked on ur issue and came up with this piece of code. Hope I understood your issue correctly.
The contraints in my code are
File format is .doc and not .xls.
Secondly, The file is saved in a static location and not the user specified location[can be optimized].
And, the code uses ActiveX and I didnot check the working in server-side environment.
These need to be addressed in the upcoming versions. (:
Peace.
Is your javascript AJAX which fetches the document.writeln() content from the server, or are you already generating that content when the page is served to the user ? Because if it's the former, I see no reason why you can't save any variables / queries in the session of whatever server-side technology your using and then just generate the plain text stuff from those. Otherwise, you'll have to folow voyager's suggestion above.
Since you're using Ext JS, you probably have a Store object that provides data to the grid? You should be able to extract the data you need by walking through the Store, and then format it the way you want. I don't think scraping the data from the generated HTML is ideal.
Once you grab the data you need from the grid and format it into text, you could POST it to the backend to initiate a download (with Content-Disposition: attachment etc.)
If you're not concerned with being cross-browser, you can also use the data: URL scheme to initiate a download without involving the backend.
This plugin does the job. Tested on IE, FF & Chrome.
https://github.com/dcneiner/Downloadify

Categories

Resources