Angular: How to download a file from HttpClient?

后端 未结 6 1612
挽巷
挽巷 2020-12-04 23:57

I need download an excel from my backend, its returned a file.

When I do the request I get the error:

TypeError: You provided \'undefined\' wh

6条回答
  •  旧巷少年郎
    2020-12-05 00:06

    After spending much time searching for a response to this answer: how to download a simple image from my API restful server written in Node.js into an Angular component app, I finally found a beautiful answer in this web Angular HttpClient Blob. Essentially it consist on:

    API Node.js restful:

       /* After routing the path you want ..*/
      public getImage( req: Request, res: Response) {
    
        // Check if file exist...
        if (!req.params.file) {
          return res.status(httpStatus.badRequest).json({
            ok: false,
            msg: 'File param not found.'
          })
        }
        const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);
    
        if (!fs.existsSync(absfile)) {
          return res.status(httpStatus.badRequest).json({
            ok: false,
            msg: 'File name not found on server.'
          })
        }
        res.sendFile(path.resolve(absfile));
      }
    

    Angular 6 tested component service (EmployeeService on my case):

      downloadPhoto( name: string) : Observable {
        const url = environment.api_url + '/storer/employee/image/' + name;
    
        return this.http.get(url, { responseType: 'blob' })
          .pipe(
            takeWhile( () => this.alive),
            filter ( image => !!image));
      }
    

    Template

     
    

    Component subscriber and use:

    @ViewChild('photo') image: ElementRef;
    
    public LoadPhoto( name: string) {
        this._employeeService.downloadPhoto(name)
              .subscribe( image => {
                const url= window.URL.createObjectURL(image);
                this.image.nativeElement.src= url;
              }, error => {
                console.log('error downloading: ', error);
              })    
    }
    

提交回复
热议问题