Angular doesn't download a file from a stream ( StreamingResponseBody )

▼魔方 西西 提交于 2021-01-24 02:52:39

问题


I'm using angular to download big files, for the backend I'm using spring boot, here's the code of the end point:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody download(@PathVariable String path) throws IOException {

    final InputStream file =azureDataLakeStoreService.readFile(path);
    return (os) -> {
        readAndWrite(file , os);
    };
}

private void readAndWrite(final InputStream is, OutputStream os)
        throws IOException {
    byte[] data = new byte[2048];
    int read = 0;
    while ((read = is.read(data)) >= 0) {
        System.out.println("appending to file");
        os.write(data, 0, read);
    }
    os.flush();
}

When I try to get the file using curl it works, and I can see the file being downloaded and it's size increasing:

curl -H "Authorization: Bearer <MyToken>" http://localhost:9001/rest/api/analyses/download --output test.zip

However, when I try to download a file using angular it doesn't work, even though the request is successful, and I can see in the logs the text "appending to file" showing multiple times, but nothing is downloading on the browser, here's my code:

this.http.get(url, { headers: headers, responseType: 'blob', observe: 'response' })
    .subscribe(response => {
        const contentDispositionHeader: string = response.headers.get('Content-Disposition');
        const parts: string[] = contentDispositionHeader.split(';');
        const filename = parts[1].split('=')[1];
        const blob = new Blob([response.body], {
            type: 'application/zip'
        });
        saveAs(blob, filename);
    });

saveAs() belong to file-saver, btw the above code works when I try to download a file as a byte[] ( without streaming ).

All I can find in the internet is this code and it's using angularJs while I'm using angular 5, Can anybody point the problem! thanks.

UPDATE:

I can see that the file is being downloaded in the network tab of Google chrome, but I have no idea where the file is being saved.


回答1:


I tried using your backend code, but in angular I used this :

window.location.href = "http://localhost:9001/rest/api/analyses/download";

And it start downloading successfully.




回答2:


It's seems that I missed arround with headers, while saving, this is the final version, it may help someone else:

Spring Boot

Add these configurations to ApplicationInit:

@Configuration
public static class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(-1);
        configurer.setTaskExecutor(asyncTaskExecutor());
    }

    @Bean
    public AsyncTaskExecutor asyncTaskExecutor() {
        return new SimpleAsyncTaskExecutor("async");
    }

}

And this to your controller:

@RequestMapping(value = "{analyseId}/download", method = RequestMethod.GET, produces = "application/zip")
public ResponseEntity<StreamingResponseBody> download(@PathVariable Long analyseId) throws IOException {
    try {
        Analyse analyse = analyseService.getAnalyse(analyseId);

        final InputStream file =azureDataLakeStoreService.readFile(analyse.getZippedFilePath());
        Long fileLength = azureDataLakeStoreService.getContentSummary(analyse.getZippedFilePath()).length;
        StreamingResponseBody stream = outputStream ->
                readAndWrite(file , outputStream);

        String zipFileName = FilenameUtils.getName(analyse.getZippedFilePath());
        return ResponseEntity.ok()
                .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + zipFileName)
                .contentLength(fileLength)
                .contentType(MediaType.parseMediaType("application/zip"))
                .body(stream);
    } catch (Exception e) {
        e.printStackTrace();
        return ExceptionMapper.toResponse(e);
    }
}

private void readAndWrite(final InputStream is, OutputStream os)
        throws IOException {
    byte[] data = new byte[2048];
    int read = 0;
    while ((read = is.read(data)) >= 0) {
        os.write(data, 0, read);
    }
    os.flush();
}

Angular

download(id) {
    let url = URL + '/analyses/' + id + '/download';
    const headers = new HttpHeaders().set('Accept', 'application/zip');
    const req = new HttpRequest('GET', url, {
        headers: headers,
        responseType: 'blob',
        observe: 'response',
        reportProgress: true,
    });
    const dialogRef = this.dialog.open(DownloadInProgressDialogComponent);
    this.http.request(req).subscribe(event => {
        if (event.type === HttpEventType.DownloadProgress) {
            dialogRef.componentInstance.progress = Math.round(100 * event.loaded / event.total) // download percentage
        } else if (event instanceof HttpResponse) {
            dialogRef.componentInstance.progress = 100;
            this.saveToFileSystem(event, 'application/zip');
            dialogRef.close();
        }
    });
}

private saveToFileSystem(response, type) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition');
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].split('=')[1];
    const blob = new Blob([response.body], {
        type: type
    });
    saveAs(blob, filename);
}


来源:https://stackoverflow.com/questions/53366704/angular-doesnt-download-a-file-from-a-stream-streamingresponsebody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!