2016-12-10 17 views
0

我正在使用jquery.filedownload插件與asp網頁API下載文件並顯示錯誤信息從服務器。jquery文件下載沒有回調工作

我已經安裝插件,並添加cookies來我的反應在GitHub上指示:https://github.com/johnculviner/jquery.fileDownload

我的文件被成功下載,但是回調不工作。

的js

var url = "/WebApi/PayrollBatches/GetBatchCsv?batchId=" + batchId; 
$.fileDownload(url, { 
successCallback: function (url) { 
     alert('success'); 
}, 
failCallback: function (responseHtml, url) { 
     alert('error'); 
} 
}); 
return false; 
//this is critical to stop the click event which will trigger a normal file download! 

的Asp網頁API

 [HttpGet] 
    public async Task<HttpResponseMessage> GetBatchCsv(int batchId) 
    { 
     string csv; 
     try { 
      using (var Dbcontext = new RossEntities()) { 
       PayrollBatchExport dal = new PayrollBatchExport(Dbcontext); 
       csv = await dal.GetBatchCsv(batchId); 
      } 
     } 
     catch (Exception ex) { 
      HttpError myCustomError = new HttpError(ex.Message) { { "CustomErrorCode", 42 } }; 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError); 
     } 

     var cookie = new CookieHeaderValue("fileDownload", "true"); 
     var cookiePath = new CookieHeaderValue("path", "/"); 
     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 

     response.Content = new StringContent(csv); 
     response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); 
     response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
     response.Content.Headers.ContentDisposition.FileName = "Export.csv"; 
     response.Headers.AddCookies(new CookieHeaderValue[] { cookie, cookiePath }); 
     response.StatusCode = HttpStatusCode.OK; 

     return response; 
    } 

編輯

下面是我的瀏覽器控制檯看起來在服務器錯誤響應像500:

enter image description here

回答

1

好吧,花了一些時間與提琴手後,問題是與cookie。注意jquery.fileDownload.js在這個代碼:

function checkFileDownloadComplete() { 
    //has the cookie been written due to a file download occuring? 

    var cookieValue = settings.cookieValue; 
    if (typeof cookieValue == 'string') { 
     cookieValue = cookieValue.toLowerCase(); 
    } 

    var lowerCaseCookie = settings.cookieName.toLowerCase() + "=" + cookieValue; 

    if (document.cookie.toLowerCase().indexOf(lowerCaseCookie) > -1) { 

     //execute specified callback 
     internalCallbacks.onSuccess(fileUrl); 
... 

成功回調被稱爲只有當服務器作爲項目頁說返回一個cookie,但是API控制器沒有正確返回這個cookie。此代碼的工作很適合我,並且還描述了official docs

public class PayrollBatchesController : ApiController 
{ 
    [HttpGet] 
    public async Task<HttpResponseMessage> GetBatchCsv(int batchId) 
    { 
     string csv; 
     try 
     { 
      string path = System.Web.HttpContext.Current.Request.MapPath(@"~\Files\testfile.csv"); 
      csv = File.ReadAllText(path);// await dal.GetBatchCsv(batchId); 

     } 
     catch (Exception ex) 
     { 
      HttpError myCustomError = new HttpError(ex.Message) { { "CustomErrorCode", 42 } }; 
      HttpResponseMessage errorResponse = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError); 
      errorResponse.Content = new StringContent("error: " + ex.ToString()); 
      return errorResponse; 
     } 

     HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 

     // Set Cookie 
     var cookie = new CookieHeaderValue("fileDownload", "true"); 
     cookie.Expires = DateTimeOffset.Now.AddDays(1); 
     cookie.Domain = Request.RequestUri.Host; 
     cookie.Path = "/"; 
     response.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 

     // ------------- 
     response.Content = new StringContent(csv); 
     response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); 
     response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
     response.Content.Headers.ContentDisposition.FileName = "Export.csv"; 
     response.StatusCode = HttpStatusCode.OK; 

     return response; 
    } 
} 

請注意,用於演示目的,我不是從DAL但是從測試的文件上面的代碼顯示檢索CSV數據。同時,爲了完整這裏,我附上客戶端代碼:

<body> 
    <div> 
     <button id="btn" type="button">get</button> 
    </div> 
    <script src="~/Scripts/fileDownload.js"></script> 
    <script> 
     $(document).ready(function() { 
      $('#btn').click(function() { 
       var url = "/api/PayrollBatches/GetBatchCsv?batchId=1"; 
       $.fileDownload(url, { 
        successCallback: function (url) { 
         alert('success'); 
        }, 
        failCallback: function (responseHtml, url) { 
         alert('error'); 
        } 
       }); 
       return false; 
      }); 
     }); 
    </script> 
</body> 

編輯:失敗回調

+0

將採取的外觀和恢復。謝謝 – JustLearning

+0

成功回調正在工作。問題在於,即使服務器返回500,成功回調也總是受到攻擊。哪種破壞了我爲什麼使用此插件的全部要點。在您的測試場景中,您是否設法通過failCallback獲取錯誤消息? – JustLearning

+0

@JustLearning我不是管理失敗的場景,但讓我檢查:) –