0

I have angular 7 app with spring boot at the back end, i save files in resourse folder, and i et trobles with downloading them. this my controller :

@RequestMapping(value = "/getfile", method = RequestMethod.POST)
    public void getFile(@RequestBody long id, HttpServletResponse response) {
        try {
            FileExpense fileExpense = fileExpenseRepo.findById(id).orElseThrow(() -> new CustomException(String.format("Договор (id:%s) не найден", id)));
                    if(fileExpense != null) {
                        File fileDownload = new File(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
                        response.setHeader("Content-Dispasition", "attachment; filename=" + fileExpense.getFileName());
                        response.setContentType("application/vnd.ms-excel");

                        OutputStream outputStream = response.getOutputStream();

                        Path path = Paths.get(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
                        byte[] data = Files.readAllBytes(path);
                        outputStream.write(data);
                        outputStream.flush();
                    }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }

and angular service:

public getFile(id: number): Observable<any> {
    return this.http.post('/expense/getfile', id);
  }

and download function in component:

downloadFile(fileJson: FileExpenseJson){
    this.expenseService.getFile(fileJson.id).subscribe(data => {
      let blob = new Blob([data.blob], {type: 'application/vnd.ms-excel'});
      let url = window.URL.createObjectURL(blob);
      let filename = fileJson.fileName;
      if (navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        let a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      }
      window.URL.revokeObjectURL(url);
    });
  }

this gives me error: message: "Unexpected token P in JSON at position 0" Please help . thanx anyway)

clutch 77
  • 1
  • 2
  • Does this answer your question? [Angular: How to download a file from HttpClient?](https://stackoverflow.com/questions/51682514/angular-how-to-download-a-file-from-httpclient) – R. Richards Jan 04 '21 at 20:22
  • 1
    https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2-or-greater – JackyShows Jan 04 '21 at 20:30
  • I saw this questions, they didn't help me , whole problem i think in front end downloading proccess – clutch 77 Jan 04 '21 at 20:33

1 Answers1

0

I found a solution: Trouble was that i not send options from front-end with response-type : 'blob' . It was sending me default json , not a blob

clutch 77
  • 1
  • 2