Skip to content

Instantly share code, notes, and snippets.

@nerdyman
Last active November 23, 2022 13:10
Show Gist options
  • Save nerdyman/237eef73347a04463125a3185d1669b2 to your computer and use it in GitHub Desktop.
Save nerdyman/237eef73347a04463125a3185d1669b2 to your computer and use it in GitHub Desktop.
Fetch a file and respect and server's Content-Disposition header
import { saveAs } from 'file-saver';
/**
* Download a file using `filename` specified in `content-disposition` header
* @param {string} url - URL to request
* @param {Object} fetchProps - Optional addtional props to pass to `fetch`
* @example
* await downloadFile('https://example.com/myfile', { credentials: 'include' })
*/
export async function downloadFile(url, fetchProps) {
try {
const response = await fetch(url, fetchProps);
if (!response.ok) {
throw new Error(response);
}
// Extract filename from header
const filename = response.headers.get('content-disposition')
.split(';')
.find(n => n.includes('filename='))
.replace('filename=', '')
.trim()
;
const blob = await response.blob();
// Download the file
saveAs(blob, filename);
} catch (error) {
console.error('Failed to download file', error);
throw new Error(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment