Akshat Sood
Akshat Sood

Reputation: 375

Downloading a file from Angular and Spring MVC API

I'm trying to download a file on the click of a button in Angular. The file that gets downloaded but is 0 KB in size and does not open.

This is the code that I have so far in Angular and Spring MVC

Angular :

public downloadFile(fileName:string){
    console.log("ready to download");
    let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
    this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
      (data) => {
        let b:Blob = new Blob([data])
        //,{type: 'application/octet-stream',}
       // const fileName :string= "RL.xlsx" 
        var url = window.URL.createObjectURL(b);
        const a : HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
       // const a = document.createElement('a');
        document.body.appendChild(a);
        a.href = url;
        a.download = fileName; 
        a.click();
        document.body.removeChild(a);
       URL.revokeObjectURL(url);
      }
    )
  }

Spring MVC :

@GetMapping(value = "/getFile")
     public @ResponseBody byte[] getFile() throws IOException {
           try {
                return messageAttachmentService.getFile(Integer.parseInt(request.getParameter("messageId")), request.getParameter("attachmentName"));
           } catch (NumberFormatException e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                logger.error(sw.toString());
           } catch (Exception e) {
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                logger.error(sw.toString());
           }
           return null;
     }

Right now when I click the button, the file gets downloaded but it's 0 KB in size and does not open. I was using type as application/octet-stream before since the file to be downloaded could be either a PDF or text file or xls. I referred to other questions too and tried changing the response type to arraybuffer. That didn't solve the issue either. What is wrong with my code?

Upvotes: 2

Views: 743

Answers (2)

Adrita Sharma
Adrita Sharma

Reputation: 22213

You can try with file-saver package. It is easy to use.

import * as FileSaver from 'file-saver';

const blob: any = new Blob([data], { type: 'octet/stream' });
saveAs(blob, "hello world.txt");

Upvotes: 2

Yash Rami
Yash Rami

Reputation: 2327

You can try like this.

  public downloadFile(fileName:string){
    console.log("ready to download");
    let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
    this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
      (data) => {
          const a = document.createElement('a');
          document.body.appendChild(a);
          const blob: any = new Blob([data], { type: 'octet/stream' });
          const url = window.URL.createObjectURL(blob);
          a.href = url;
          a.download = data.fileName;
          a.click();
          window.URL.revokeObjectURL(url);
      }
    )
  }

Upvotes: 0

Related Questions