I ended up here when searching for ”rxjs download file using post”.
This was my final product. It uses the file name and type given in the server response.
import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
downloadPost(url: string, data: any) {
return ajax({
url: url,
method: 'POST',
responseType: 'blob',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain, */*',
'Cache-Control': 'no-cache',
}
}).pipe(
map(handleDownloadSuccess),
);
}
handleDownloadSuccess(response: AjaxResponse) {
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(response.response);
const disposition = response.xhr.getResponseHeader('Content-Disposition');
if (disposition) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const filename = matches[1].replace(/['"]/g, '');
downloadLink.setAttribute('download', filename);
}
}
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}