如何使用JQuery处理zip文件的强制下载


How to handle the forced download of zip file using JQuery

我使用的是带有POST数据的REST API。我正在创建一个zip文件并进行强制下载。我需要通过使用JQuery发送所需的POST数据来调用该API,然后JQuery将获得下载。我怎样才能做到这一点?

您可以这样做:

HTML:

<input type="button" class="list" value="Download ZipFile" id="download"/>

JS:

$("#download").click(function(){
  //this is the data when you send your request 
    var data = { yourKey1 :'something1', yourKey2:'something2'};
  // this is a fake response that we are assumming you got from ajax's response inside success call back 
  var response = {fileName:'yourFileName.zip' ,filePath : 'YouFilePath'};
  $.ajax({
        type: "POST",
        url: 'yourURL',
        data: data,
        success: function(response) {
           download(response);
       }
   }); 
});
var download = function (data){
  var link = document.createElement('a');
    link.href = data.filePath + data.fileName ;
    //below you can define a new name
    link.download = data.fileName;
    document.body.appendChild(link);
    link.click();
}

示例:https://jsfiddle.net/3yjt4Lah/8/