簡體   English   中英

Angular 4從Spring Boot服務器下載文件

[英]Angular 4 download a file from a spring boot server

我正在使用帶有angular4頭版的Spring Boot服務器。 我有一項服務,可以使用HttpClient從前端下載.zip文件。 這是我的代碼:

角度服務:

getZip(fileName: string) : Observable<any> {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/zip',
        'Accept': 'application/zip'
      }),
      params: new HttpParams().set('fileName', fileName),
      reponseType: 'blob'
    };
    return this.http.get<Blob>(extractZip, httpOptions);
  }

角服務電話:

this.myService.sendSql(this.sql, this.dataSource, this.fileGeneration).subscribe(data => {
      if(this.fileGeneration) {
        this.myService.getZip(data.zipName).subscribe(blob => {
        console.log(blob);
        console.log("Zip file download success.")
        },
        error => {
        console.log(error);
        console.log("Zip file download failed.")
        });
      }
    },
    err => {
        console.log('An error occured when contacting application server.');
    });

因此,基本上,我使用this.myService.sendSql()獲得將與this.myService.getZip()一起使用以下載zip的zip名稱。

我的請求是這樣的: http://localhost:8870/extracts_sql?fileName=name.zip ,在我的瀏覽器中它可以正常工作。

這里是服務器端代碼:

@GetMapping("/extracts_sql")
    public ResponseEntity<InputStreamResource> getFile(@RequestParam String fileName) throws FileNotFoundException {
        Configuration configuration = ConfigurationHelper.readConfiguration(configurationFile);
        MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, fileName);
        File file = new File(configuration.getProcessingFolder() + File.separatorChar + fileName);
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        //Resource file = this.sqlToolService.loadFile(fileName, configuration);
        log.i("Sending zip :"+fileName+" to user.");

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(mediaType)
                .contentLength(file.length())
                .body(resource);
    }

問題是即使我的狀態HttpErrorResponse = 200,我HttpErrorResponse在有角度的一側得到HttpErrorResponse ,這是錯誤: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse Http failure during parsing for http://localhost:8870/extracts_sql?fileName=name.zip什么想法嗎?

返回此:

return this.http.get<Blob>(extractZip, httpOptions)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM