Search code examples
.netangular.net-coreangular2-forms

How to parse C# FileContentResult in Typescript


I'm working on an Angular 2 app where we allow the user to download a Word document. Right now it's working, but the name that comes back is a long string/GUID. I need the actual name of the file that was downloaded. Here's our setup:

on the client side:

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');
    }
  });
}

the service call:

getDocument(docKey: string): Observable<any> {
    return this._http.get(`${this._env.systemApi}/Document/GetDocument/${docKey}`, { responseType: 'arraybuffer' });
}

Back end call:

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);
}

so in the console, I can see that when the data comes back in to the subscribe method that there are three arrays, which I think correspond to the AttachmentBinary, MimeDataType, and AttachmentName, but I'm not sure how to parse out the name.

Here's what the return data looks like in dev tools:

enter image description here

I inherited this, and I haven't worked with Blob data before, so kind of stuck.


Solution

  • I figured it out, needed to add:

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

    to the back end code.