2016-03-29 73 views
0

我正在使用REST API和POST數據。我正在創建一個zip文件並進行強制下載。我需要通過使用JQuery發送所需的POST數據來調用該API,然後應該獲得下載。我怎樣才能做到這一點?如何處理使用JQuery強制下載zip文件

回答

0

你可以這樣做:

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/