Reputation: 33
I am working on a web project. I use Spring Boot and Angular 2. I want to create CSV file and download this file on client pc from server. I use Apache Poi to create the CSV file. When I click on the 'Export CSV' button I can pass from frontend to backend via service and I can create the CSV file on the server successfully. Here is service code:
exportCSVFileTest(parameter: string): Observable<any> {
return this.httpService.post( super.getAddrApi() + parameter , null )
.catch( err => {
if (!err.status) {
err = {
status: Observable.throw(401)
};
}
return Observable.throw(err);
});
}
After I use this service, I create the CSV file on server and I try to download this file on client's pc from server:
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=" + file.getName());
FileInputStream is = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
while(is.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
is.close();
out.flush();
out.close();
After that I don't get any error. Everything seems fine however the window that should appear for the file uploading process does not appear. I tried different methods, for example I set content type application/csv
or text/csv
. And I tried 'OutputStream', 'response.getWriter().write()
' vs. What am I doing wrong?
Upvotes: 3
Views: 912
Reputation: 314
To download a file you need to tell the browser it is a download, I know 2 ways to do this:
1 - Download the file using a link in the HTML
<a [routerLink]="['url/to/download/the/file']">Download CSV</a>
2 - Get the file using your service and downloading with saveAs library
import {saveAs} from 'file-saver';
this.service.exportCSVFileTest('parameter').subscribe(response => {
const filename = 'name of the file.csv';
saveAs(response.blob(), filename);
})
Hope this help.
Upvotes: 1