Ошибка загрузки файла (служба angular spring boot)

загрузка файлов с angular8 и spring boot. Сервисная часть Spring Boot работала с Postman. Но когда я загружаю с помощью angular, я получаю сообщение об ошибке. ошибка

Он не отображается в разделе console.log (Файл ответа:, ответ).

 downloadFile(event) {
        this.additionalDocumentService.getFileDownload(event.fileId).subscribe(response => {
          console.log("File response:",response)
          this.downloadFile = response;
    
          
        });
      }
      

   getFileDownload(fileId: number): Observable<any> {
    return this.http.get(apiHost + '/downloadFile/' + fileId);

  }

@RequestMapping("/downloadFile/{dosyaId}")
        public ResponseEntity<HttpStatus> handleFileDownloadPage(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "fileId") Integer fileId) throws IOException, Exception {
    
           
            File file = fileService.getFileId(fileId);
            
            if (StringUtils.hasText(dosya.getFilePath())) {
    
                ServletOutputStream out = response.getOutputStream();
    
                InputStream stream = null;
                try {
    -
                    stream = new FileInputStream(file.getFilePath());
                   
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", String.format(" attachment; filename=\"%s\"", file.getFileName()));
    
                    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    out.flush();
    
                } catch (Exception e) {
                    System.err.println(e.toString());
                } finally {
                    out.close();
                    if (stream != null) {
                        stream.close();
                    }
                }
                return null;
    
            }
            return ResponseEntity.ok(HttpStatus.OK);
        }

person zdnmn    schedule 08.03.2021    source источник
comment
Можете ли вы добавить метод getDosyaIndir к вопросу?   -  person Keshavram Kuduwa    schedule 09.03.2021
comment
getDosyaIndir =getFileDownload, сори, была орфографическая ошибка.   -  person zdnmn    schedule 10.03.2021


Ответы (1)


Следующая функция примет любой тип файла и всплывающее окно загрузки:

downloadFile(route: string, filename: string = null): void{

    const baseUrl = 'http://myserver/index.php/api';
    const token = 'my JWT';
    const headers = new HttpHeaders().set('authorization','Bearer '+token);
    this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
        (response: any) =>{
            let dataType = response.type;
            let binaryData = [];
            binaryData.push(response);
            let downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
            if (filename)
                downloadLink.setAttribute('download', filename);
            document.body.appendChild(downloadLink);
            downloadLink.click();
        }
    )
}
person Keshavram Kuduwa    schedule 10.03.2021