【问题标题】:How to parse C# FileContentResult in Typescript如何在 Typescript 中解析 C# FileContentResult
【发布时间】:2020-03-11 20:18:10
【问题描述】:

我正在开发一个允许用户下载 Word 文档的 Angular 2 应用程序。现在它正在工作,但返回的名称是一个长字符串/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);
}

所以在控制台中,我可以看到当数据返回到订阅方法时,有三个数组,我认为它们对应于 AttachmentBinary、MimeDataType 和 AttachmentName,但我不确定如何解析出名字。

以下是开发工具中返回数据的样子:

我继承了这个,而且我以前没有处理过 Blob 数据,所以有点卡住了。

【问题讨论】:

  • 显示getDocument()fn
  • getDocument 是后端代码

标签: .net angular .net-core angular2-forms


【解决方案1】:

您可以在响应请求中设置带有文件名的标题。

Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", FileName));

【讨论】:

  • 但是那是在 AttachmentName 中返回的,我正试图弄清楚一旦它被传回后如何到达它
【解决方案2】:

我想通了,需要补充:

Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

到后端代码。

【讨论】:

    猜你喜欢
    • 2016-12-05
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2020-10-13
    • 1970-01-01
    • 2022-12-24
    相关资源
    最近更新 更多