use*_*418 5 excel entity-framework webclient-download asp.net-web-api
我正在尝试通过 Web API(使用实体框架)下载 excel 文件。下载正在运行,但我在尝试打开文件时收到一些关于文件损坏的错误对话框。
Web API 代码如下:
public HttpResponseMessage GetValue(int ID, string name)
{
MemoryStream stream;
try {
using (DataContext db = new DataContext()) {
dynamic fileObj = (from c in db.FileList c.ID == IDc).ToList();
stream = new MemoryStream(fileObj(0).File);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(fileObj(0).FileContentType);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = name };
return result;
}
} catch (Exception ex) {
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
Run Code Online (Sandbox Code Playgroud)
它打开带有两个错误对话框和以下消息的文件。
Excel 完成了文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃
我遇到了同样的问题,问题不在 Web api 代码中,而是在客户端代码中。对我来说,我使用的是jquery。以下代码为我修复了它。
我正在根据结果创建一个 blob,这不是必需的,因为结果已经是一个 blob。
window.URL.createObjectURL(result);
Run Code Online (Sandbox Code Playgroud)
请注意,我是直接根据结果创建对象。完整的 Jquery 代码如下。
$.ajax({
type: 'POST',
url: url + "/download",
data: data,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'
return xhr;
},
success: function (result, status, xhr) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var link = document.createElement('a');
link.href = window.URL.createObjectURL(result);
link.download = filename;
link.click();
}, error: function (a, b) {
console.log('Error');
}
});
Run Code Online (Sandbox Code Playgroud)