Tuesday, January 29, 2013

Cool Javascript to Download a File

Found this really cool snippet that you can use to download a file with javascript. It uses a technique to insert a hidden iframe on to the page and then streams the file directly by using the file url as the url of the iframe.

Now you can use logic in your page to trigger downloads of different files.

This is the function you can use and I found it on this web page: http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery


var downloadURL = function downloadURL(url)
                        {
                            var hiddenIFrameID = 'hiddenDownloader',
                            iframe = document.getElementById(hiddenIFrameID);
                           
                            if (iframe === null)
                            {
                                iframe = document.createElement('iframe');
                                iframe.id = hiddenIFrameID;
                                iframe.style.display = 'none';
                                document.body.appendChild(iframe);
                            }
                            iframe.src = url;
                        };

No comments:

Post a Comment