Skip to content
Advertisement

How can i implement download file From API

I can’t download file from my friend service java code from angular that i implement and i don’t know how to implement download file from angular please help me

My Code Angular

    private _download$ = new Subject<void>();
    **this._download$.pipe(switchMap(()=>this._downloadFile())).subscribe(resultBlob =>{
        console.log("Success to Next ")
        this.loadFile(resultBlob)
    },(exception:any)=>{
        console.log("exception: ",exception)
    },()=>{
        console.log("Complete: ")
    })
}**

**private _downloadFile(){
    const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type':  'application/octet-stream',
          responseType : 'blob',
          Accept : 'application/octet-stream',
          observe : 'response'
        })
      };**
    return this.http.get<Blob>('/col-corecollection-service/exclusion/download-file/'+this.exclusionCode,httpOptions)
}
private download(){
    this._download$.next();
}
loadFile(data: any) {
    var blob = new Blob([data], {type: 'application/octet-stream'});
    var downloadURL = window.URL.createObjectURL(data);
    window.open(downloadURL);
}**

And I have code service that my friend implement like this

@GetMapping("/exclusion/download-file/{exclCode}")
  @ResponseStatus(HttpStatus.OK)
  public ResponseEntity<Resource> exclusionDownloadFile(
    @Size(min = 1, max = 50)
    @PathVariable String exclCode
  ) {
    if (!this.exclusionService.existsExclusionById(exclCode)) {
      throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Exclusion code " + exclCode + " not found.", null);
    }
    SearchExclFilenameExclBlobByIdResponse downloadFile = this.exclusionService.searchExclFilenameExclBlob(exclCode);
    byte[] fileData = downloadFile.getExclBlob();
    Resource resource = new InputStreamResource(new ByteArrayInputStream(fileData));
    return ResponseEntity.ok()
      .contentType(MediaType.APPLICATION_OCTET_STREAM)
      .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="" + downloadFile.getExclFilename() + """)
      .body(resource);
  }

when i click my download button and then it can’t downloadFile to me please help

Advertisement

Answer

Try passing responseType outside headers

Remove responseType from header:

const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/octet-stream',
      Accept : 'application/octet-stream',
      observe : 'response'
    })
  };

Here is updated code for passing responseType outside headers:

return this.http.get<Blob>('/col-corecollection-service/exclusion/download-file/'+this.exclusionCode,{headers: httpOptions.headers, responseType: 'blob'})

Then if you want download use fileSaver:

var file = new Blob([data], { type: "application/octet-stream" });
            this.fileSaverService.save(file);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement