Let's say I have download links for files on my site.
When clicked these links send an AJAX request to the server which returns the URL with the location of the file.
What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?
We do it that way:
First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
download
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter.
We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
I have created an open source jQuery File Download plugin (Demo with examples) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:
User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
Tested cross browser support (including mobile!)
It supports POST and GET requests in a manner similar to jQuery's AJAX API
successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
Just call window.location.href = new_url from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar
Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.
It may seem obvious to some but some may simply copy/paste this code:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So what happens if I pass something like '/path/to/fileWithSecrets' to this script?
The given script will happily send any file the webserver-user has access to.
Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
Try this lib https://github.com/PixelsCommander/Download-File-JS it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience.
Explained here - http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-type/
Seems to be ideal piece of code for starting downloading in JavaScript.
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
To get around the security flaw in the top-voted answer, you can set the iframe src directly to the file you want (instead of an intermediate php file) and set the header information in an .htaccess file:
<Files *.apk>
ForceType application/force-download
Header set Content-Disposition attachment
Header set Content-Type application/vnd.android.package-archive
Header set Content-Transfer-Encoding binary
</Files>
I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.
Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.
In relation to the top answer I have a possible solution to the security risk.
<?php
if(isset($_GET['path'])){
if(in_array($_GET['path'], glob("*/*.*"))){
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
}
}
?>
Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.
~Note: Javascript / HTML~
HTML:
<iframe id="download" style="display:none"></iframe>
and
<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">
JavaScript:
<script type="text/javascript">
<!--
function ChangeSource(path){
document.getElementByID('download').src = 'path_to_php?path=' + document_path;
}
-->
</script>
I'd suggest window.open() to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).
Why are you making server side stuff when all you need is to redirect browser to different window.location.href?
Here is code that parses ?file= QueryString (taken from this question) and redirects user to that address in 1 second (works for me even on Android browsers):
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
(window.onload = function() {
var path = urlParams["file"];
setTimeout(function() { document.location.href = path; }, 1000);
});
</script>
If you have jQuery in your project definitely remove those window.onpopstate & window.onload handlers and do everything in $(document).ready(function () { } );
Related
I have to create a online time-table for the school. The part what is troubling me at the moment is not to be able to download a file by clicking on the filename.
I try to download a file by clicking on a button or a link with html/php maybe javascript but for javascript I should somehow combine php and javascript because javascript has no readfile-function.
Some of my attempts:
Download
This just shows the content of the file in the web browser but I am not able to download it. The content of my testmove.txt is testmove123, so I just see the text testmove123 in my browser.
Another example:
Javascript:
function download(file)
{
window.location=file;
}
+html:
<input type="button" value="Download" onClick="download('dateiupload/testmove.txt')" >
Makes the same.
Another example:
Javascript:
function download(path)
{
var ifrm = document.getElementById("frame");
ifrm.src = path;
}
+html:
<iframe id="frame" style="display:none"></iframe>
download
By clicking on "Download" the javascript function starts but nothing else happens and I see the same site.
Another example (with php):
Javascript:
function download(path)
{
var ifrm = document.getElementById(frame);
ifrm.src = "download.php?path="+path;
}
+html (same as above):
<iframe id="frame" style="display:none"></iframe>
download
+php (the reason my its more or less working):
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
This solution doesn't wait for a click from me and starts the download by starting the site.
A working solution I thought about would be to link to another site where the download automatically starts but its absolutely not how it have to be. I use $_POST variables on the site and I lose them when I leave the site and I can't come back after the download.
It must start the download by clicking on the filename.
You can download straight from the anchor tag by using the 'download' attribute.
<a href="dateiupload/testmove.txt" download>Download</a>
The filename of the downloaded file will be testmove.txt by default.
You can change the filename like this.
Download
More Details at w3Schools
You were correct to use those headers - as you can see, the file is being downloaded. The only problem now is to have it download when you want it to.
For a very simple solution, I would suggest setting up a download.php file that will be the page you download all files from. You would setup a GET parameter for this file and the URL would look something like this:
http://your-cool-site.com/download.php?filename=textmove.txt
Now inside download.php, you'll read that GET parameter which will be a filename, and then pass it eventually to the readfile function. This is the stage that you should think about enforcing some level of security as passing a path directly to the function could give people access to files that they shouldn't be looking at! Think about limiting the actual downloadable files to a limited selection of files or paths you know to be "safe" for people to download.
You'll also need to use the file name in the headers (and possibly even the size of the file to support displaying progress of the download).
Once you have this download.php file ready, you can place links to it from other pages in a very similar way that you have now:
Download File
Clicking on this link will make the request to download.php and when it gets the appropriate headers, the download will start.
I'm having a form that once submitted, the PHP generates a PDF file and sends it to the client. Everything works fine so far. What I'm having trouble with is that I need to trigger window.print() on the window containing the received pdf. Is there a way to make the printing wizard appear for the received pdf file?
Here is the code I have
//The #options is a form that once submitted is sends the requested PDF to the browser
$('#options').on('submit', function(e){
if($(this).find('[name="action"]').val() == 'print')
{
var url = $(this).attr('action') || document.URL;
e.preventDefault();
$.post(url, $(this).serializeArray(),function(pdf){
// Open the printing wizard for the requested document
});
}
else
{
// The PDF is displayed normally
return true;
}
});
I'm not even sure if what I want to do is possible. Is is possible for example to open the PDF in a new tab and call window.print() there?
One easy approach for this is to put the PDF file in a new iFrame.
Then you can print the complete content inside the iframe using window.print(); function.
<html>
<head>
<title>Print Test Page</title>
<script>
function printPDF() {
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
Some content here
<iframe name=print_frame width=0 height=0 frameborder=0 src=about:blank>
Your PDF is loaded here
</iframe>
Some more content here
</body>
</html>
Now call window.print(); function when you want to print your pdf.
To open PDF in new window, you need to essentially generate an GET request (so that window can be open via URL) - one of the simple way is to code your server side code to accept the input parameters via query string. Better way is to use POST request (as you are currently doing) to generate the PDF at the server side and cache it in temp location, then return some token/ticket (e.g. it can be as simple as temp file name) to the browser. This token would be used in GET request to get the PDF file - GET request would go to server that would simply read the file off temp location and return it back as inline ((i.e. header content-disposition: inline;). Then you may try window.print() to print it. Similar ways can be used with iframe (with contentWindow.print()).
However, you may find that these solutions may not work - for example, there is no PDF plugin to display the PDF inline (or user has chosen always open file externally). Or it may not work across browser. So yet another (and IMO better) way is to embed java-script within PDF it self to instruct for print as soon as the file is opened.
For example, see this PHP code example that would embed java-script in PDF generation for auto printing - the example is using FPDF for PDF generation.
This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.
I am aware of the hidden iFrame trick as mentioned here (http://stackoverflow.com/questions/365777/starting-file-download-with-javascript) and in other answers.
I am interested in a similar problem:
How can I use Javascript to download the current page (IE: the current DOM, or some sub-set of it) as a file?
I have a web page which fetches results from a non-deterministic query (eg. a random sample) to display to the user. I can already, via a querystring parameter, make the page return a file instead of rendering the page. I can add a "Get file version" button (our standard approach) but the results will be different to those displayed because it is a different run of the query.
Is there any way via Javascript to download the current page as a file, or is copying to the clipboard my only option?
EDIT
An option suggested by Stefan Kendall and dj_segfault is to write the result server side for later retrieval. Good idea, but unfortunately writing files server side is out of the question in this instance.
How about shudder passing the innerHTML as a post parameter to another page?
You can try with the protocol data:text/attachment
Like in:
<html>
<head>
<style>
</style>
</head>
<body>
<div id="hello">
<span>world</span>
</div>
<script>
(function(){
document.location =
'data:text/attachment;,' + //here is the trick
document.getElementById('hello').innerHTML;
//document.documentElement.innerHTML; //To Download Entire Html Source
})();
</script>
</body>
</html>
Edit after shesek comment
To add to Mic's terrific answer above, some additional points:
If you have Unicode content (Or want to preserve indentation in the source), you need to convert the string to Base64 and tell the Data URI to treat the data as such:
(function(){
document.location =
'data:text/attachment;base64,' + // Notice the new "base64" bit!
utf8_to_b64(document.getElementById('hello').innerHTML);
//utf8_to_b64(document.documentElement.innerHTML); //To Download Entire Html Source
})();
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
utf_to_b64() via MDN -- works in Chrome/FF.
You can drop this all into an anchor tag, allowing you to set the download attribute:
<a onclick="$(this).attr('href', 'data:text/plain;base64,' + utf8_to_b64($('html').clone().find('#generate').remove().end()[0].outerHTML));" download="index.html" id="generate">Generate static</a>
This will download the current page's HTML as index.html and removes the link used to generate the output. This assumes the utf8_to_b64() function from above is defined somewhere else.
Some useful links on Data URIs:
MDN article
MSDN article
Depending on the size and if support is needed for ancient browsers, but you can consider creating a dynamic file using data: URIs and link to it. I'be seen several places that do that. To get the brorwser to download rather than display it, play around with the content type you put in the URI and use the new html5 download attribute. (Sorry for any typos, I'm writing from my phone)
I don't think you're going to be able to do it exactly the way you want to. JavaScript can't create a file and download it for security reasons. Nor can it create it on the server for download.
What I would do if I were you is, on the server side, create an output file with the session ID in the name in a temp directory as you create the output for the web page, and have a button on the web page with a link to that file.
You'll probably want a separate process to remove files over a day old or something like that.
Can you not cache the query results, and store it by some key? That way you can reference the same report output forever, or until your file garbage collector comes along. This also implies that you can create static URLs to report outputs, which tends to be nice.
I've been using the Microsoft Technet site and you can download the ISO files by clicking a link on the page. The element is like this:
<a href="javascript:void(0)" onmouseout="HideToolTip()"
onmouseover="ShowToolTip(event,'Click here to download.')"
onclick="javascript:RunDownload('39010^313^164',event)"
class="detailsLink">Download</a>
I wasn't able to find the RunDownload() method in the scripts. And I wondered what it is likely to do. I mean usually when I provide a link for someone to download I provide an anchor to it:
download
But this is working differently what is the script doing? Because even when I ran 'Fiddler' I wasn't able to see the actual download location.
there's no such thing as a "javascript download" link. Javascript can open a new window, or simulate a click on a link.
What you have to find is which url the function triggered by this click will lead to.
here's an example of how to do it:
Suppose we have a:
<a id="download">download Here ยงยงยง</a>
then this jQuery code:
$('#download').click( function() {
window.location.href = 'http://example.org/download/ISO.ISO';
} );
will redirect to the URL http://example.org/download/ISO.ISO. Whether this url starts a download or not depends on HTTP headers and your browser, not on what javascript do.
Download location can be a url-rewritten path. This mean that maybe some parameters are given with HTTP Post and some HTTP handler in the Web server or web application may be getting some arguments from the HTTP request and write file bytes to an HTTP response, which absolutely hides where the file is located in the actual server's file system.
Maybe this is what's behind the scenes and prevents you to know the file location.
For example, we can have this:
http://mypage.com/downloads/1223893893
And you requested an executable like "whatever.exe" for downloading it to your hard disk. Where's the "http:/mypage.com/downloads/whatever.exe"? Actually, it doesn't exist. It's a byte array saved in a long database in some record, and "mypage" web application handles a request for a file that's identified as "1223893893" which can be a combination of an identifier, date time or whichever argument.
What I think the function RunDownload might do is that it might inform the server using get request to the server that another download is about to happen , or it might need to run the download background by setting the target attribute to an iframe so the user won't need to open another tab and download the file on the same page.
Download
JS
var runDownload=function(){
e.preventDefault();
increaseDownloadCountOnTheServer(location);
window.location.href="filelocation.exe";
}