Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download a PDF via POST with Fetch API
let fnGetFileNameFromContentDispostionHeader = function (header) {
let contentDispostion = header.split(';');
const fileNameToken = `filename*=UTF-8''`;
let fileName = 'downloaded.pdf';
for (let thisValue of contentDispostion) {
if (thisValue.trim().indexOf(fileNameToken) === 0) {
fileName = decodeURIComponent(thisValue.trim().replace(fileNameToken, ''));
break;
}
}
return fileName;
};
let postInfo = {
id: 0,
name: 'foo'
};
let headers = new Headers();
headers.append('Content-Type', 'application/json');
fetch(`api/GetPdf`, {
method: 'POST',
headers: headers,
body: JSON.stringify(postInfo)
})
.then(async res => ({
filename: fnGetFileNameFromContentDispostionHeader(res.headers.get('content-disposition')),
blob: await res.blob()
}))
.then(resObj => {
// It is necessary to create a new blob object with mime-type explicitly set for all browsers except Chrome, but it works for Chrome too.
const newBlob = new Blob([resObj.blob], { type: 'application/pdf' });
// MS Edge and IE don't allow using a blob object directly as link href, instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(newBlob);
} else {
// For other browsers: create a link pointing to the ObjectURL containing the blob.
const objUrl = window.URL.createObjectURL(newBlob);
let link = document.createElement('a');
link.href = objUrl;
link.download = resObj.filename;
link.click();
// For Firefox it is necessary to delay revoking the ObjectURL.
setTimeout(() => { window.URL.revokeObjectURL(objUrl); }, 250);
}
})
.catch((error) => {
console.log('DOWNLOAD ERROR', error);
});
@dradovic
Copy link

dradovic commented Jul 4, 2020

Use resObj.filename as a 2nd parameter to msSaveOrOpenBlob to get the filename right in IE and Edge.

@RodolfoSilva
Copy link

RodolfoSilva commented Aug 10, 2020

Thanks @devloco, I made some changes and added Typescript.

function getFileNameFromContentDispostionHeader(
  contentDisposition: string,
): string | undefined {
  const standardPattern = /filename=(["']?)(.+)\1/i;
  const wrongPattern = /filename=([^"'][^;"'\n]+)/i;

  if (standardPattern.test(contentDisposition)) {
    return contentDisposition.match(standardPattern)[2];
  }

  if (wrongPattern.test(contentDisposition)) {
    return contentDisposition.match(wrongPattern)[1];
  }
}

function saveBlob(fileName: string, blob: Blob) {
  // MS Edge and IE don't allow using a blob object directly as link href, instead it is necessary to use msSaveOrOpenBlob
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
    return;
  }

  // For other browsers: create a link pointing to the ObjectURL containing the blob.
  const objUrl = window.URL.createObjectURL(blob);

  let link = document.createElement('a');
  link.href = objUrl;
  link.download = fileName;
  link.click();

  // For Firefox it is necessary to delay revoking the ObjectURL.
  setTimeout(() => {
    window.URL.revokeObjectURL(objUrl);
  }, 250);
}

interface Options {
  url: string;
  body?: BodyInit;
  onDownloadProgress?: (receivedLength: number, contentLength: number) => void;
  fetchOptions?:
    | RequestInit
    | ((fetchOptions: RequestInit) => Promise<RequestInit>);
}

export async function downloadFile(options: Options) {
  const {
    url,
    onDownloadProgress,
    fetchOptions,
    body,
  } = options;

  let requestInit: RequestInit = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
    body,
  };

  if (typeof fetchOptions === 'function') {
    requestInit = await fetchOptions(requestInit);
  } else if (typeof fetchOptions === 'object') {
    requestInit = { ...requestInit, ...fetchOptions };
  }

  const response = await fetch(url, requestInit);

  if (!response.ok) {
    const responseBody = await response.text();
    throw new Error(responseBody ?? 'Error try again');
  }

  const reader = response.body.getReader();

  const contentLength = Number(response.headers.get('Content-Length'));

  let receivedLength = 0;
  const chunks = [];
  while (true) {
    const { done, value } = await reader.read();

    if (done) break;

    chunks.push(value);
    receivedLength += value.length;

    if (typeof onDownloadProgress !== 'undefined') {
      onDownloadProgress(receivedLength, contentLength);
    }
  }

  const type = response.headers.get('content-type')?.split(';')[0];

  // It is necessary to create a new blob object with mime-type explicitly set for all browsers except Chrome, but it works for Chrome too.
  const blob = new Blob(chunks, { type });

  const contentDisposition = response.headers.get('content-disposition');

  const fileName = getFileNameFromContentDispostionHeader(contentDisposition);

  return {
    fileName,
    blob,
  };
}

interface DownloadAndSaveFileOptions extends Options {
  defaultFileName: string;
}

export default async function downloadAndSaveFile(
  options: DownloadAndSaveFileOptions,
) {
  try {
    const { defaultFileName, ...rest } = options;

    const { fileName, blob } = await downloadFile(rest);

    saveBlob(fileName ?? defaultFileName, blob);
  } catch (error) {
    console.log('DOWNLOAD ERROR', error);
  }
}

@dradovic
Copy link

dradovic commented Sep 1, 2020

FYI. This approach does not work for Safari 12.1.

Switched altogether to https://github.com/eligrey/FileSaver.js which solves this problem but kept the getFileNameFromContentDispostionHeader method is proved useful.

@Nextt1
Copy link

Nextt1 commented Nov 5, 2020

If your response type is CORS and then you might need to allow content-disposition header from the server by adding an extra header - https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

@dsaw
Copy link

dsaw commented Aug 16, 2021

Note the

if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(newBlob);
        }

does not seem to be needed on Edge 92.0.902.73. (not tested on older browsers though so advisable to not leave it out)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment