2017-03-27 9 views
1

Ich habe ein Problem mit der Datei von Spring Boot mit angular2 herunterladen.Spring Boot Angular2 Datei Download funktioniert nicht

Hier ist mein Code von Spring Boot, kam aus: Return generated pdf using spring MVC. Ich kann Datei dirrectly mit Postbote herunterladen, aber nicht mit angular2 ...

@RequestMapping(value="/file/{id}", method=RequestMethod.GET) 
public ResponseEntity<?> getFile(@PathVariable("id") long id) { 
    UploadFile uFile = uploadFileService.getUploadFileById(id); 


    byte[] contents = uFile.getContent(); 

    HttpHeaders headers = new HttpHeaders(); 
    headers.setContentType(MediaType.parseMediaType("application/pdf")); 
    headers.setContentDispositionFormData(uFile.getName(), uFile.getName()); 
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); 

    return new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK); 
} 

Angular2 Service

downloadFile(id: number){ 
    let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'}); 
    headers.append('Authorization',this.auth.token); 
    let options = new RequestOptions({ headers: headers, responseType: ResponseContentType.Blob}); 

    return this.http.get(this.editUrl + id, options) 
    .map(res => {return new Blob([res.blob()],{ type: 'application/pdf' })}); 
} 

Und Download-Button

downloadFile(uFile: UploadFile){ 
    this.uploadFileService.downloadFile(uFile.id) 
     .subscribe(
       data => window.open(URL.createObjectURL(data)), 
      ); 
    return false; 
} 

Wenn ich Download-Button klicken Chrom öffnet neuen Tab und sofort schließt es keine Datei anzeigen. Und hier sind einige Antwortheader vom Postboten.

Access-Control-Allow-Headers →Content-Type, x-requested-with, Authorization, responseType 
Access-Control-Allow-Methods →POST, PUT, GET, PATCH, OPTIONS, DELETE 
Access-Control-Allow-Origin →http://localhost:4200 
Access-Control-Max-Age →3600 
Cache-Control →must-revalidate, post-check=0, pre-check=0 
Content-Disposition →form-data; name="reference.pdf"; filename="reference.pdf" 
Content-Length →31576 
Content-Type →application/pdf 
Date →Mon, 27 Mar 2017 08:39:24 GMT 
X-Content-Type-Options →nosniff 
X-Frame-Options →DENY 
X-XSS-Protection →1; mode=block 
+1

Überprüfen Sie diese beiden Antworten, schrieb ich darüber: http://Stackoverflow.com/questions/37046133/pdf-blob-is-not-showing-content-angular-2/39657478#39657478 und http://stackoverflow.com/questions/40300252/angular2-displaying-pdf/40300966#40300966 –

+1

Ja das sind genau die Codes, die ich in meiner Lösung verwendet habe, aber das Problem tritt immer noch auf. Wenn ich versuche, Datei in IE zu downloaden, öffnet es neue Registerkarte Whitlink so etwas wie: Blob: 8ASDA017-7456B-4614-AD56-47456456021 – user3551808

+1

Es funktioniert nicht in IE, nur in Chrome und Mozilla, soweit ich weiß. –

Antwort

Verwandte Themen