【问题标题】:Download zip file with jquery from ajax post request从 ajax 发布请求下载带有 jquery 的 zip 文件
【发布时间】:2014-07-03 19:30:23
【问题描述】:

我想知道是否可以对特定 url 进行 ajax 发布请求并仅在请求时接收数据中的 zip 文件?或者我必须发送两个请求……一个是为了在已创建的服务器中获取 zip 文件的 url,另一个是为了下载 zip 文件?

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    当然可以!但是只有新的浏览器支持这个。

    var url = 'test.zip';
    var filename = 'test.zip';
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'blob';
    request.onload = function() {
       var link = document.createElement('a');
       document.body.appendChild(link);
       link.href = window.URL.createObjectURL(request.response);
       link.download = filename;
       link.click();
    };
    request.send();
    

    【讨论】:

    • 随着文件大小达到几兆字节,浏览器是否有崩溃的可能性?用户会看到下载进度吗?我想他不会 - 如果我得到正确的解决方案......
    • @SimonSimCity 查看FileSaver 库,这应该让您对大小限制有所了解。您可以通过 xhr 进度事件跟踪下载进度,请参阅MDN doc
    【解决方案2】:

    本机答案是否定的!

    但是你可以这样做。

    您的 ajax 请求:

    $.ajax({
        url: 'your-url-that-gives-zip-file.php',
        dataType: 'JSON',
        success: function(response){
            if(response.zip) {
                location.href = response.zip;
            }
        }
    });
    

    你的 php 文件:

    <?php
    
    //Get your zip file code with and combine with http://youradress.com
    
    $zipFile = 'http://youraddress.com/downloads/'.$zipFile;
    
    echo json_encode(array('zip' => $zipFile));
    
    ?>
    

    【讨论】:

    • thxx man....你节省了一天....已经用了大约 2.5 小时....再次感谢
    【解决方案3】:

    您无法使用 ajax 下载文件。

    如果您只想要一个请求,那么放弃 ajax 并将隐藏的 iframe 附加到页面,并将 php 文件作为其源。

    不过,这将限制您使用获取请求。

    例如:

    $('#id').click(function(){
    
        $(body).append('<iframe style="display:none;" src="yourfile.php?key=value"></iframe>');
    
    });
    

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 1970-01-01
      • 2018-08-31
      • 2021-10-02
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多