How to get file name from content-disposition
Here is how I used it sometime back. I'm assuming you are providing the attachment as a server response.
I set the response header like this from my REST service response.setHeader("Content-Disposition", "attachment;filename=XYZ.csv");
function(response, status, xhr){
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
}
EDIT:
Editing the answer to suit your question- use of the word inline
instead of attachment
function(response, status, xhr){
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('inline') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
}
}
}
More here
This is an improvement on marjon4's answer.
A much simplified way to the selected answer would be to use split like this;
var fileName = xhr.getResponseHeader('content-disposition').split('filename=')[1].split(';')[0];
Note: This solution may not work as expected if your file name itself contains a semi-colon (;)
In my case the header looks like this:
attachment; filename="test-file3.txt"
Therefore I was able to extract the filename pretty easily with a named group regexp:
const regExpFilename = /filename="(?<filename>.*)"/;
const filename: string | null = regExpFilename.exec(contentDispositionHeader)?.groups?.filename ?? null;
I know I'm slightly off topic here as OP doesn't have the quotes around the filename but still sharing in case someone comes across the same pattern as I just did
Or simply just:
var fileName = xhr.getResponseHeader('Content-Disposition').split("filename=")[1];