-
-
Save nerdyman/237eef73347a04463125a3185d1669b2 to your computer and use it in GitHub Desktop.
Fetch a file and respect and server's Content-Disposition header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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