Reputation: 1867
I have some changes related to other thing but suddenly when i am downloading file from api
i am getting below error
@Injectable()
export class FileDownloadService {
constructor(private httpClient: HttpClient) { }
public downloadFile(data: HttpResponse<Blob>) {
const contentDisposition = data.headers.get('content-disposition');
const filename = this.getFilenameFromContentDisposition(contentDisposition);
const blob = data.body;
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.download = filename;
anchor.href = url;
anchor.click();
}
private getFilenameFromContentDisposition(contentDisposition: string): string {
const regex = /filename=(?<filename>[^,;]+);/g;
const match = regex.exec(contentDisposition);
const filename = match.groups['filename'];
return filename;
}
}
controller:
download() {
this.dataService.download(this.fileName)
.pipe(takeUntil(this.unsubscribe$))
.subscribe({
next: (blobresponse: any) => {
this.downloadService.downloadFile(blobresponse);
}, error: (error:any) => { }
});
}
Error:
Not donwloading file entire application..I have chehcked api but response (file) is coming from api.. Please let me know what i did wrong..it is perfectly fine last week..pls suggest me i am checking from last 24 hrs. but no where find solution..
EDIT: May be issue with contentdecoposition
Upvotes: 1
Views: 4172
Reputation: 1867
In .net 6 some i have inlcuded corepolicy. now code working..it may help some other net 6..Thank you @dmitryro
services.AddCors(options =>
{
options.AddDefaultPolicy(builder => builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithExposedHeaders("Content-Disposition") ----This line i have added
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials());
});
Upvotes: 2
Reputation: 3516
You have to do the null check:
private getFilenameFromContentDisposition(contentDisposition: string): string {
const regex = /filename=(?<filename>[^,;]+);/g;
const match = regex.exec(contentDisposition);
let filename = null; // or any other value you consider default
if (typeof match !== 'undefined' && match !== null) {
filename = match.groups['filename'];
}
return filename;
}
Upvotes: 1