I\'ve written code that uses Angular $http to download a file. The name of the file is not specified in the URL. The URL contains a unique identifier for the file, wh
// SERVICE
downloadFile(params: any): Observable<HttpResponse<any>> {
const url = `https://yoururl....etc`;
return this.http.post<HttpResponse<any>>(
url,
params,
{
responseType: 'blob' as 'json',
observe: 'response' as 'body'
})
.pipe(
catchError(err => throwError(err))
);
}
// COMPONENT
import * as FileSaver from 'file-saver';
... some code
download(param: any) {
this.service.downloadFile(param).pipe(
).subscribe({
next: (response: any) => {
let fileName = 'file';
const contentDisposition = response.headers.get('Content-Disposition');
if (contentDisposition) {
const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = fileNameRegex.exec(contentDisposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
}
const fileContent = response.body;
FileSaver.saveAs(fileContent, fileName);
},
error: (error) => {
console.log({error});
}
});
}
Enjoy
Similar to some of the above answers but using a basic RegEx is how I solved it instead:
let fileName = parseFilenameFromContentDisposition(response.headers('Content-Disposition'));
function parseFilenameFromContentDisposition(contentDisposition) {
if (!contentDisposition) return null;
let matches = /filename="(.*?)"/g.exec(contentDisposition);
return matches && matches.length > 1 ? matches[1] : null;
}
If response.headers('Content-Disposition')
returns null, use response.headers.**get**('Content-Disposition');
.
The rest of @andrew's snippet now works great.
Maybe you already find solution, but I will post this answer if someone else has this problem.
Add these parameters in the success callback function from the $http request:
$http.get(myUrl).success(function (data, status, headers, config) {
// extract filename from headers('Content-Disposition')
});
Use response.headers
to get http response headers:
$http.get(myUrl).then(function (response) {
// extract filename from response.headers('Content-Disposition')
}
success(function(data, status, headers, response,xhr) {
console.log(headers('Content-Disposition'));
}