locked
How to download Excel template file from folder attachment using angular 7? RRS feed

  • Question

  • User696604810 posted

    I work on project angular 7 and web API asp.net core 2.2 I face issue I can't get Template Excel file

    Exist on Server found on folder Attachment and file Name Delivery.xlsx to download it .

    I only Need When click on download Button download Template Excel file from folder attachment

    my issue How to get file Delivery.xlsx from attachment Folder and assign it on angular 7 to download ?

    component.html
    
        <input type="button" class="btn btn-success" value="Download" (click)="download()" style="margin: 20px 0;"/>
    component.ts
    
    download(file) {
          
        let fileName = ???;
        let checkFileType = fileName.split('.').pop();
        var fileType;
       
        if (checkFileType == ".xlsx") {
            fileType = "application/vnd.openxmlformats officedocument.spreadsheetml.sheet";
        }
        
        this.DownloadFile(fileName, fileType)
            .subscribe(
                success => {
                    saveAs(success, fileName);
                },
                err => {
                    alert("Server error while downloading file.");
                }
            );
    }
    
    DownloadFile(filePath: string, fileType: string): Observable<any> {
    
        let fileExtension = fileType;
        let input = filePath;
    
        return this.http.get('https://localhost:44396/api/ApprovalQuality/download'+ "?fileName=" + input, {
           
            responseType: 'blob',
            observe: 'response'
        })
            .pipe(
                map((res: any) => {
                    return new Blob([res.body], { type: fileExtension });
                })
            );
    }
    Web API .net core 2.2
    
    [HttpGet]
            [Route("Download")]
            public IActionResult Download(string FileName)
            {
                return File(memory, ex.GetContentType(path), Path.GetFileName(path));
            }

    Monday, November 23, 2020 2:23 AM

All replies

  • User-474980206 posted

    your angular code can not write to the file system except via local storage. the most common trick to save a blob, is to convert it to a data url, and assign as the href of an anchor. then javascript can cll the click event. (requires browser support data url navigation). 

    the other common approach is anchor navigation or a browser form post to target="_blank", and the server return the file as an attachment.

    let a = document.getElementById('downloader');
    if (!a) {
       a = document.createElement('a');
       a.id = 'downloader';
       a.target = '_blank'; 
       a.style.visibility = "hidden";
       document.body.appendChild(a);
    }
    a.href = 'https://localhost:44396/api/ApprovalQuality/download?fileName=' + input;
    a.click();
    

    -- bruce

    Monday, November 23, 2020 5:01 PM