开发者

How to download multiple files in one shot in IE

I want to download multiple files on click of a button in jsp.

I am using the following code in the js to call one servlet twice.

var iframe = document.createElement("iframe");
iframe.width = iframe.height = iframe.frameBorder = 0;
iframe.scrolling =开发者_如何学JAVA "no";
iframe.src = "/xyz.jsp?prodId=p10245";
document.getElementById("iframe_holder").appendChild(iframe);

var iframe2 = document.createElement("iframe");
iframe2.width = iframe2.height = iframe2.frameBorder = 0;
iframe2.scrolling = "no";
iframe2.src = "/xyz.jsp?prodId=p10243";
document.getElementById("iframe_holder").appendChild(iframe2);

In xyz.jsp i am calling the servlet which downloads the file from a path and send it on the browser.

Issue is that it is working safari,firefox but not in IE.

We cannot download multiple files with IE?


By design, non-user-initiated file downloads are blocked in IE. That inherently means that it should not be possible to download more than one file as the result of a single user-click.


I've used the following code to download multiple files in IE and Chrome

function downloadFile(url)
{
    var iframe = document.createElement("iframe");
    iframe.src = url;
    iframe.style.display = "none";
    document.body.appendChild(iframe);
}

function downloadFiles(urls)
{
    downloadFile(urls[0]);
    if (urls.length > 1)
        window.setTimeout(function () { downloadFiles(urls.slice(1)) }, 1000);
}

You pass an array of URLs to the downloadFiles() function, which will call downloadFile() for each with a short delay between. The delay seems to be the key to getting it to work!


I had a similar need but also wanted the downloads to occur in a new window.

I created a js to download a list of files, and a php to do the actual file saving. I used the above as a starting point, and the PHP start from (okay, can't find the original source). I encode the passed URI so spaces in the file names don't cause troubles.

(function () {
"use strict";

var files = [],              // Array of filename strings to download
newWindow,                   // New window to handle the download request
secondsBetweenDownloads;     // Wait time beteen downloads in seconds
//
//  Download a file using a new window given a URI
//
  function downloadFile(uri) {
    if (!newWindow) {
        newWindow = window.open('',
            '',
            'width=1500 height=100');
    }
    if (newWindow) {
        newWindow.location =
            'saveAs.php?' +
            'file_source=' + encodeURI(uri);
        newWindow.document.title = "Download File: " + uri;
    } else {
        console.log("Unable to open new window.  Popups blocked?");
    }
}
//
//  Download all files specified in the files[] array from siteName.
//  Download the file at array position zero, then set a timeout for
//  secondsBetweenDownloads seconds
//
function downloadFiles(siteName) {
    var showTime = new Date();

    console.log(
            showTime.toTimeString().substring(0,8)  +
            " Starting download for: " + files[0]
        );
    // Skip any empty entries, download this file
    if (files[0].length > 0) downloadFile(siteName + files.splice(0, 1));  
    if (files.length > 0) {                     // If more files in array
             window.setTimeout(function () {    // Then setup for another iteration
                downloadFiles(siteName );
            }, secondsBetweenDownloads * 1000); // Delay for n seconds between requests
     } else {
        newWindow.close();                      // Finished, close the download window
     }
}
//
//  Set the web site name and fill the files[] array with the files to download
//  then kick off the download of the files.
//
$(document).ready(function () {
    var
    siteName** = "http://www.mysteryshows.com/thank-you/";
    secondsBetweenDownloads** = 35;   // N seconds delay between requests

    files = [
        "show1.mp3",
        "show2.mp3"
   ];
    downloadFiles(siteName, files);
});
}());

The HTML for the page is simple. Basically any syntax-compliant page will do.

The saveAs.php page which the js file uses in the newWindow.location line is php only.

     <?php
    if (isset($_GET['file_source'])) {
        $fullPath = $_GET['file_source'];
        if($fullPath) {
            $fsize = filesize($fullPath);
            $path_parts = pathinfo($fullPath);
            $ext = strtolower($path_parts["extension"]);
            switch ($ext) {
                case "pdf":
                header("Content-Disposition: attachment;
                filename=\"".$path_parts["basename"]."\""); // use 'attachment' to 
                                                            // force a download
                header("Content-type: application/pdf"); // add here more headers for 
                                                         // diff. extensions
                break;
                default;
                header("Content-type: **application/octet-stream**");
                header("Content-Disposition: 
                   filename=\"".$path_parts["basename"]."\"");
            }
            if($fsize) {//checking if file size exist
                header("Content-length: $fsize");
            }
            $request = $path_parts["dirname"] . '/' .
                rawurlencode($path_parts["basename"]);
            readfile($request);
            exit;
        }
    }
?>

I used rawurlencode on just the 'basename' portion of the URI to ensure it was a valid, encoded request.


It can be done by creating a blob using the file source URL. I have tested this with image and PDF files in IE 11.

                if (navigator.msSaveBlob) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('GET', file_url, true);
                    xhr.responseType = 'blob';

                    xhr.onload = function(e) {
                       if (this.status == 200) {
                           var blob = this.response;
                           navigator.msSaveBlob(blob, file_name);
                       }
                    }

                    xhr.onerror = function(e) {
                        alert("Error " + e.target.status + " occurred while receiving the document.");
                    }

                    xhr.send();
                }

I got this idea when I came across this: Getting BLOB data from XHR request

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜