How To Download All File Format With Angular And .Net Core Web API

Introduction

In this article, we will learn about how to download all file format with angular and .NetCore Web API.

We can better understand this step by step.

Step 1

First of all, create one method "DownloadDocument" and pass arguments as FilePath like,

async DownloadDocument(fileDownloadPath: string) {
    this.fileUrl = fileDownloadPath; //"wwwroot/SiteDocument/SiteDemo1/FileDocument.doc" static file path
    this.siteDocumentUploadService.DocumentsDownload(this.fileUrl).subscribe(async (event) => {
        let data = event as HttpResponse < Blob > ;
        const downloadedFile = new Blob([data.body as BlobPart], {
            type: data.body?.type
        });
        console.log("ddd", downloadedFile)
        if (downloadedFile.type != "") {
            const a = document.createElement('a');
            a.setAttribute('style', 'display:none;');
            document.body.appendChild(a);
            a.download = this.fileUrl;
            a.href = URL.createObjectURL(downloadedFile);
            a.target = '_blank';
            a.click();
            document.body.removeChild(a);
        }
    });
}

Note: File download folder path start with wwwroot and then rest inside folder for example.

FirstFolder is SiteDocument Child Folder is SiteName SiteDemo1 and then FileName so path will be like,

  • : wwwroot/SiteDocument/SiteDemo1/FileDocument.doc // Document
  • : wwwroot/SiteDocument/SiteDemo1/FileExcel.xls // Excel
  • : wwwroot/SiteDocument/SiteDemo1/FilePDF.pdf // Pdf

Step 2

For calling service DocumentDownload Function, call server API Like,

DocumentsDownload(fileUrl: string) {
    return this.http.get(`${environment.apiUrl}` + this.getSiteDocumentsUrl + "/DocumentsDownload?fileUrl=" + fileUrl, {
        reportProgress: true,
        observe: 'events',
        responseType: 'blob'
    });
}

Step 3

Now we create API Fetch File from Directory and return as File to Client like,

[HttpGet, DisableRequestSizeLimit]
[Route("DocumentsDownload")]
public async Task < IActionResult > DocumentsDownload([FromQuery] string fileUrl) {
    var filePath = Path.Combine(Directory.GetCurrentDirectory(), fileUrl);
    if (!System.IO.File.Exists(filePath)) return NotFound();
    var memory = new MemoryStream();
    await using(var stream = new FileStream(filePath, FileMode.Open)) {
        await stream.CopyToAsync(memory);
    }
    memory.Position = 0;
    return File(memory, GetContentType(filePath), filePath);
}
private string GetContentType(string path) {
    var provider = new FileExtensionContentTypeProvider();
    string contentType;
    if (!provider.TryGetContentType(path, out contentType)) {
        contentType = "application/octet-stream";
    }
    return contentType;
}

Conclusion

Nowadays some applications require downloading file with different format like pdf, document, excel, csv and png/jpeg so this article is very helpful for easy to file download from server. 

Enjoy Coding !!!!

We have got the response. Fantastic! The post helpful for file download from server angular with .netCore API.

Thank you for reading my article. Please leave your comments in the comment box below.