![](/img/trans.png)
[英]Connect asp.net core web api with Blazor Web assembly like Angular SPA
[英]File download in angular js SPA with ASP.net web API not working properly?
我已經通過使用asp.net使用angular js和WEB API實現了Web應用程序。 我用ContentDisposition返回文件名,如下WEB API控制器方法。
try
{
if (!string.IsNullOrEmpty(fileName))
{
string filePath = HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new ByteArrayContent(bytes.ToArray());
httpResponseMessage.Content.Headers.Add("x-filename", fileName);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "" + fileName + "";
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
}
}
return this.Request.CreateResponse(HttpStatusCode.NotFound, "File not found.");
}
catch (Exception ex)
{
return this.Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
}
但是,當嘗試從客戶端訪問x文件名時,它不存在。 角度代碼如下所示。
$http({
method: 'GET',
url: common.serviceUrl(config.apiServices.usermanuals),
params: { manualId: manualId },
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
headers = headers();
//var test = headers('Content-Disposition');
var filename = headers['x-filename'];
var contentType = headers['content-type'];
var linkElement = document.createElement('a');
try {
var blob = new Blob([data], { type: contentType });
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
} catch (ex) {
console.log(ex);
}
}).error(function (data) {
console.log(data);
});
返回標題如下所示
文件名未定義我如何從這里訪問ContentDisposition。 請幫助
謝謝
在控制器中添加了以下代碼,從而解決了該問題。
hiddenHeaders:“ x文件名”
[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "x-filename")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.