Iñigo
Iñigo

Reputation: 2016

Download PDF from byte[]

Server side (Visual Studio 2015)

I have a pdf stored in my server side. When called from the client via WebApi, I read and store the content on a variable with this instruction:

byte[] bytes = File.ReadAllBytes(path);

Then I send the file content to the client with the following instruction:

return Request.CreateResponse(HttpStatusCode.OK, bytes);

Client side (Angular 7) With FileSaver installed I receive the file content and it looks like this

JVBERi0xLjUNCiW1tbW1DQoxIDAgb2Jq...eXBlL0NhdGFsb2cvUG

Then I try to download it in the following way:

this.fileService.fileDownload().subscribe(bytes => {
    const file = new Blob([bytes], {type: 'application/pdf'});
    saveAs(file, 'file.pdf');
}

With the following method in the fileService calling the Server API:

fileDownload(id): Observable<HttpResponse<any>>{
    const httpOptions = {
      'responseType'  : 'arraybuffer' as 'json'
    };
    return this.http.get<any>('http://localhost:55820/api/files/12',httpOptions);
  }

But the file is corrupted or not admited by Acrobat Reader.

I would also like it to work for other file types, having the file content in byte[], the content-type definition (text/plain, application/pdf) and the file name with the extension. How can I standarize this process?

Upvotes: 1

Views: 1458

Answers (2)

Shreesh Mishra
Shreesh Mishra

Reputation: 1

Response Type should be like responseType: 'blob' and after getting the blob response from observable you can pass blob response in the downloadFile(content) function where we will give type(E.g pdf, zip, etc) of file and name of the file and create an event to download.

download(id): Observable<Blob> {
    return this.http.get(this.downloadUrl + id 
    { 
        headers: this.getHeaders(), responseType: 'blob' })
        .pipe(catchError(this.handleError<any>('download')));
    }

this.downloadService.download(id).subscribe(data => {
    this.downloadFile(data);
});

downloadFile(content) {
    const fileName = 'dowmloadfile.pdf';
    const type = 'pdf';
    const e = document.createEvent('MouseEvents');
    const a = document.createElement('a');
    a.download = fileName;
    a.href = window.URL.createObjectURL(content);
    a.dataset.downloadurl = [type, a.download, a.href].join(':');
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
}

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22203

httpOptions should be { responseType: 'blob' }

Try like this:

fileDownload(id): Observable<HttpResponse<any>>{
    return this.http.get('http://localhost:55820/api/files/12',{ responseType: 'blob' });
}



this.fileService.fileDownload().subscribe(bytes => {
    saveAs(file, 'file.pdf');
}

Upvotes: 1

Related Questions