How to download multiple files in one shot in IE

前端 未结 4 987
Happy的楠姐
Happy的楠姐 2021-01-05 05:40

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.c         


        
相关标签:
4条回答
  • 2021-01-05 05:59

    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.

    0 讨论(0)
  • 2021-01-05 05:59

    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.

    0 讨论(0)
  • 2021-01-05 06:06

    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!

    0 讨论(0)
  • 2021-01-05 06:08

    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 讨论(0)
提交回复
热议问题