我无法通过 Web API 下载由 closedxml 创建的 excel 文件。如果我将文件保存在服务器上,它看起来不错,但是一旦我将它放入流中并将其返回到 web api,那么浏览器中只会收到一个损坏的文件。
正如我在几个帖子中所建议的那样,我使用 httpResponseMessage,但在浏览器中,标头中的文件名永远不会到达。
我们正在使用:
"Microsoft.AspNet.WebApi" 版本="5.2.3" targetFramework="net461
"ClosedXML" version="0.88.0" targetFramework="net461"
网页API代码:
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Parcel List");
MemoryStream fs = new MemoryStream();
wb.SaveAs(fs);
fs.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(fs.GetBuffer());
result.Content.Headers.ContentLength = fs.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "List" + "_" + DateTime.Now.ToShortDateString() + ".xlsx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
这里的javascript代码:
context.$http.post(config.get_API_URL() + 'api_call', excel_list,
{responseType: 'application/octet-stream'})
.then(
success_function,
error_function)
}
成功功能:
function(response) {
var headers = response.headers;
var blob = new Blob([response.body],
{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
);
window.open(window.URL.createObjectURL(blob));
}
问题似乎是 web api 调用的响应类型必须是 {responseType: 'arraybuffer'} 而不是 {responseType: 'application/octet-stream'}
context.$http.post('api-url', excel_list, {responseType: 'arraybuffer'}) .then( success_function, error_function) }
无论如何感谢您的快速帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句