2014-10-31 71 views
1

我想要按照此example顯示進度條而不使用ajax來下載文件。不使用ajax下載文件

我使用基諾,html和webapi。我有低於該按鈕的點擊事件調用HREF代碼

this.getMeData= function() { 

    uRlPath("/api/GetSomeData?id=" + 12) 
       + "&name=" + getName.toString() 
       + "&downloadtoken=" + new Date().getTime()); 

    $('#myLink').click(); 

    location.href = $('#myLink').attr('href'); 


    }; 

這是我的HTML

<tr> 
      <td class="labelText"> 
       <button data-bind="click: getMeData"> 
        Download Data 
       </button> 

      </td> 
     </tr> 
     <tr> 
      <td> 
       <a id="myLink" data-bind="attr: { href: uRlPath }" style="visibility: hidden">Open </a> 
      </td> 
     </tr> 

我現在想請我的HREF

這是點擊事件的一些功能我的webapi方法返回我cookie和二進制文件

public HttpResponseMessage GetSomeData(int id, string name, string downloadtoken) 
    { 
     var returnData= new HttpResponseMessage(HttpStatusCode.OK); 
     returnData.Content = new ByteArrayContent(mybyteArray); 
     var cookie = new CookieHeaderValue("downloadtoken", downloadtoken); 
     returnData.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 
     returnData.Content.Headers.ContentDisposition = 
      new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
     returnData.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); 


     returnData.Content.Headers.ContentDisposition.FileName = "myfile.pdf"; 
     return returnData; 
    } 

要非常精確我想要有與示例中提供的行爲相同的行爲。在示例中,他們使用表單提交,但我沒有任何形式,因爲我只是使用HTML,淘汰賽。我已經包含了示例中提到的所有庫。

如果您需要更多輸入信息,請告訴我。

回答

1

我自己找到了解決方案。我用下面的代碼爲餅乾

var attempts = 30; 
var checkTime 

     startProgressBar(true) 

     checkTime= window.setInterval(function() { 

      var cookieValue = $.cookie('downloadtoken'); 

      if ((cookieValue == token) || (attempts == 0)){ 
       stopDownload(); 
      } 
      attempts --; 
     }, 1000); 

不斷檢查在finishDownload功能我清楚的cookie,並停止進度條

function stopDownload() { 
     window.clearInterval(checkTime); 
     $.cookie('downloadtoken', null); //clears this cookie value 
     stopProgressBar(false); 
    } 

這是進度條的html代碼

<div data-bind="visible: stopProgressBar" style="top:248px;left: 320px;"> 
    <img src="../images/ProgressBar.jpg" /> 
</div> 
0

如果你只是想調用blockUIForDownload功能鏈接被點擊的時候,你可以做一個「點擊」綁定,就像你一樣的按鈕:

<a id="myLink" data-bind="attr: {href: uRlPath}, click: blockUIForDownload" style="visibility: hidden">Open</a> 

(這是假設的功能。已經視圖模型中定義)

的「點擊」綁定這裏參見官方文檔:http://knockoutjs.com/documentation/click-binding.html

然而,在我看來像你過於複雜了一點 - 在您發佈的示例中,隱藏輸入f因爲他們使用表單輸入作爲將令牌傳輸到服務器的手段,因此需要使用該字段。

在你的情況令牌被作爲href屬性的一部分通過,所以可以大大簡化代碼:

1)拆下無形鏈路完全

2)與更換getMeData功能以下:

this.getMeData= function() { 
    window.open("/api/GetSomeData?id=" + 12 
       + "&name=" + getName.toString() 
       + "&downloadtoken=" + new Date().getTime()); 
    blockUIForDownload(); 
    }; 
+0

我需要同類的例子中提供的機制。在例子中,他們使用表單提交,我沒有任何形式提交,因爲我使用基諾和HTML。我想要的是調用按鈕上的webapi服務。此服務返回我的PDF文件。所以我想要的是顯示一些進度條或什麼東西,直到文件被下載。你提到我提供的例子嗎?另外我不能使用window.open打開新窗口。 – Happy 2014-11-03 08:06:54