我正在使用jquery.filedownload
带有ASP Web API的插件来下载文件并从服务器显示错误消息。
我已经安装了插件并按照github上的指示将cookie添加到了我的响应中:https : //github.com/johnculviner/jquery.fileDownload
我的文件已成功下载,但是回调不起作用。
s
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 Web 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时我的浏览器控制台的外观:
好的,花了一些时间在Fiddler之后,问题出在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。该代码对我来说效果很好,并且在官方文档中也有描述
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>
编辑:失败回调
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句