2017-05-10 2 views
0

Ich habe ein Problem beim Herunterladen einer Datei in meinem Angular-Projekt. Das Problem ist, dass die Datei erfolgreich heruntergeladen wird, wenn ich versuche, zur URL der Datei zu navigieren. Aber wie kann ich die Download-Funktion in Angular implementieren?Datei über Angular und TypeScript herunterladen

[VRoute("PassportAttachments/{id}", 1)] 
[HttpGet] 
[AllowAnonymous] 
public HttpResponseMessage GetPassportAttachmentById(int individualId, [FromUri] int id = -1) 
{ 
    try 
    { 
     var attachment = _passportAttachmentManager.FindById(id); 

     string attachmentPath = HttpContext.Current.Server.MapPath(
      string.Format(ConfigurationManager.AppSettings["IndividualPassportsPath"], individualId.ToString()) + attachment.FileName); 

     //string downloadUrl = Url.Content(attachmentPath).Replace("/Api/Contacts/PassportAttachments/~", ""); 

     //var result = new { DownloadUrl = downloadUrl, AttachmentTitle = attachment.Title }; 
     //return Ok(result); 
     if (File.Exists(attachmentPath)) 
      return new FileContentResult(attachmentPath, attachment.Title, FileResultType.ImageContentResult); 
     else 
      return null; 
    } 
    catch (Exception ex) 
    { 
     Unit.Logger.Error(ex, ToString(), ActionContext.ActionArguments.ToList()); 
     return null; 
     //return NotFound(); 
    } 
} 

FileContentResult Konstruktor:

public FileContentResult(string FilePath, string ResponeFileName, FileResultType fileResultType) : base(HttpStatusCode.OK) 
{ 
    var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read); 
    base.Content = new StreamContent(stream); 
    base.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachments") { FileName = ResponeFileName }; 

    switch (fileResultType) 
    { 
     case FileResultType.ZipContentResult: 
      base.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); 
      break; 
     case FileResultType.ExcelContentResult: 
      base.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
      break; 
     case FileResultType.PDFContentResult: 
      base.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); 
      break; 
     case FileResultType.ImageContentResult: 
      base.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); 
      break; 
    } 
} 

Nun wie gesagt, wenn ich die URL eingeben, um die Datei von selbst herunterlädt (daher das AllowAnonymous) alles funktioniert. Aber Funktion soll ich die Datei mit Typoskript

public DownloadAttachments(): void { 
    if (this.SelectedPassportAttachments != null && this.SelectedPassportAttachments.length > 0) { 
     if (this.SelectedPassportAttachments.length == 1) { 
      this.service.DownloadSinglePassportAttachment(this.SelectedPassportAttachments[0].Id, this.IndividualId).subscribe((file: any) => { 
       // download file (function) 
      }); 
     } 
     else { 
      this.service.DownloadMultiplePassportAttachment(this.IndividualId, this.SelectedPassportAttachments.map(pa => pa.Id), this.SelectedPassportNumber).subscribe(); 
     } 
    } 
} 
+0

Ich benutze dies als '.csv' Dateien zu erzeugen -' window.open ("api/Controller/get", '_self', ''); ' – shammelburg

Antwort

0

zum Download verwenden oder schreiben Da Sie ein Content-Disposition Header verwenden, wird der Browser automatisch einen Download-Dialog auslösen, wenn es versucht, die URL zu laden.

So können Sie entweder navigieren nur auf den Download-Standort, oder öffnen Sie die Download-Adresse in einem separaten Fenster (was in den meisten Browsern automatisch schließen, wenn der Download-Dialog erscheint):

// navigate to the URL: 
window.location.href = downloadUrl; 

// or open a new window 
window.open(downloadUrl); 

Beachten Sie, dass Das Öffnen eines Fensters wird durch Popup-Blocker blockiert, wenn Sie window.open außerhalb von Mausereignissen ausführen (zum Beispiel Tastenklicks). Sie können dies vermeiden, indem Sie das Fenster zuerst öffnen, wenn der Download-Button geklickt wird, und ändern Sie die URL später. Etwas wie folgt aus:

downloadAttachment() { 
    const downloadWindow = window.open('about:blank'); 
    this.service.GetDownloadUrl(…).subscribe(downloadUrl => { 
     downloadWindow.location.href = downloadUrl; 
    }); 
} 
Verwandte Themen