我正在使用Angular 2应用,我们允许用户下载Word文档。现在它正在工作,但是返回的名称是一个长字符串/ GUID。我需要下载的文件的实际名称。这是我们的设置:
在客户端:
downloadWordTemplate(): void {
this._data.getDocument(this.document.docKey)
.subscribe(data => {
const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = window.URL.createObjectURL(blob);
const winObj = window.open(url);
if (!winObj || winObj.closed || typeof winObj.closed === 'undefined') {
this._toastr.info('File download blocked by pop-up blocker');
}
});
}
服务电话:
getDocument(docKey: string): Observable<any> {
return this._http.get(`${this._env.systemApi}/Document/GetDocument/${docKey}`, { responseType: 'arraybuffer' });
}
后端通话:
public async Task<IActionResult> GetDocument(string docKey)
{
var document= await Task.Run(() => _context.Documents
.Where(x => x.key== docKey)
.Select(x => new
{
AttachmentName = x.WordAttachmentName,
MimeDataType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
AttachmentBinary = x.WordAttachmentBinary
}).FirstOrDefault());
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = document.AttachmentName,
Inline = true
};
Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return File(document.AttachmentBinary,
document.MimeDataType,
document.AttachmentName);
}
所以在控制台中,我可以看到,当数据返回到subscription方法时,有三个数组,我认为它们对应于AttachmentBinary,MimeDataType和AttachmentName,但是我不确定如何解析出名字。
这是开发工具中返回数据的样子:
我继承了这一点,并且我之前从未使用过Blob数据,所以有点卡住了。
您可以在响应请求中设置带有文件名的标题。
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", FileName));
我知道了,需要添加:
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
到后端代码。