download file using an ajax request

后端 未结 12 2367
旧时难觅i
旧时难觅i 2020-11-21 23:46

I want to send an \"ajax download request\" when I click on a button, so I tried in this way:

javascript:

var xhr = new XMLHttpRequest();
xhr.open(\         


        
相关标签:
12条回答
  • 2020-11-22 00:37

    Decoding a filename from the header is a little bit more complex...

        var filename = "default.pdf";
        var disposition = req.getResponseHeader('Content-Disposition');
    
        if (disposition && disposition.indexOf('attachment') !== -1) 
        {
           var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
           var matches = filenameRegex.exec(disposition);
    
           if (matches != null && matches[1]) 
               filename = matches[1].replace(/['"]/g, '');
        }
    
    0 讨论(0)
  • 2020-11-22 00:41

    Cross browser solution, tested on Chrome, Firefox, Edge, IE11.

    In the DOM, add an hidden link tag:

    <a id="target" style="display: none"></a>
    

    Then:

    var req = new XMLHttpRequest();
    req.open("GET", downloadUrl, true);
    req.responseType = "blob";
    req.setRequestHeader('my-custom-header', 'custom-value'); // adding some headers (if needed)
    
    req.onload = function (event) {
      var blob = req.response;
      var fileName = null;
      var contentType = req.getResponseHeader("content-type");
    
      // IE/EDGE seems not returning some response header
      if (req.getResponseHeader("content-disposition")) {
        var contentDisposition = req.getResponseHeader("content-disposition");
        fileName = contentDisposition.substring(contentDisposition.indexOf("=")+1);
      } else {
        fileName = "unnamed." + contentType.substring(contentType.indexOf("/")+1);
      }
    
      if (window.navigator.msSaveOrOpenBlob) {
        // Internet Explorer
        window.navigator.msSaveOrOpenBlob(new Blob([blob], {type: contentType}), fileName);
      } else {
        var el = document.getElementById("target");
        el.href = window.URL.createObjectURL(blob);
        el.download = fileName;
        el.click();
      }
    };
    req.send();
    
    0 讨论(0)
  • 2020-11-22 00:41

    Your needs are covered by window.location('download.php');
    But I think that you need to pass the file to be downloaded, not always download the same file, and that's why you are using a request, one option is to create a php file as simple as showfile.php and do a request like

    var myfile = filetodownload.txt
    var url = "shofile.php?file=" + myfile ;
    ajaxRequest.open("GET", url, true);
    

    showfile.php

    <?php
    $file = $_GET["file"] 
    echo $file;
    

    where file is the file name passed via Get or Post in the request and then catch the response in a function simply

    if(ajaxRequest.readyState == 4){
                            var file = ajaxRequest.responseText;
                            window.location = 'downfile.php?file=' + file;  
                        }
                    }
    
    0 讨论(0)
  • 2020-11-22 00:46

    I prefer location.assign(url);

    Complete syntax example:

    document.location.assign('https://www.urltodocument.com/document.pdf');
    

    developer.mozilla.org/en-US/docs/Web/API/Location.assign

    0 讨论(0)
  • 2020-11-22 00:47

    You actually don't need ajax at all for this. If you just set "download.php" as the href on the button, or, if it's not a link use:

    window.location = 'download.php';
    

    The browser should recognise the binary download and not load the actual page but just serve the file as a download.

    0 讨论(0)
  • 2020-11-22 00:51

    Update April 27, 2015

    Up and coming to the HTML5 scene is the download attribute. It's supported in Firefox and Chrome, and soon to come to IE11. Depending on your needs, you could use it instead of an AJAX request (or using window.location) so long as the file you want to download is on the same origin as your site.

    You could always make the AJAX request/window.location a fallback by using some JavaScript to test if download is supported and if not, switching it to call window.location.

    Original answer

    You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.

    $.ajax({
        url: 'download.php',
        type: 'POST',
        success: function() {
            window.location = 'download.php';
        }
    });
    

    Even though this answers the question, it's better to just use window.location and avoid the AJAX request entirely.

    0 讨论(0)
提交回复
热议问题