Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mc-funk/b73f7331f94d7269004888d10e128f74 to your computer and use it in GitHub Desktop.
Save mc-funk/b73f7331f94d7269004888d10e128f74 to your computer and use it in GitHub Desktop.
Creating a blob from a steamed file in React
const [fileURL, setFileURL] = useState<string | null>(null);
useEffect(() => {
if (!doc?.id) return;
const { id: documentUUID } = relayIdToEntityNameAndId(doc?.id);
const url = csvDownloadRoute({ documentID: documentUUID });
fetch(url)
.then(res => {
console.log('DEBUG', { res });
if (!res.body) throw new Error('No response');
return res.body;
})
.then(stream => new Response(stream))
// Create an object URL for the response
.then(response => {
console.log('DEBUG Response(stream)', { response });
return response.blob();
})
.then(blob => {
const fileLoc = URL.createObjectURL(blob);
console.log('DEBUG', { fileLoc });
setFileURL(fileLoc);
})
.catch(e => {
throw new Error(e);
});
// cleanup
// FIXME: BACK-1805 fileURL is null here, need to fully investigate what is needed to avoid leaving a bunch of blobs lying around
return () => {
console.log('DEBUG cleanup', { fileURL });
if (fileURL) URL.revokeObjectURL(fileURL);
};
}, [doc?.id]);
if (!doc) return null;
const { id: documentUUID } = relayIdToEntityNameAndId(doc?.id);
console.log({ documentUUID, fileUUID: doc?.file?.fileUUID })
return(
<Button
// Use our own a href "as" because Link doesn't work with download attribute, despite passing it down from Button.
// We could likely coordinate with mainline to improve this.
as={({ children, to, ...props }: { children: JSX.Element; to: string }) => (
<a {...props} href={to}>
{children}
</a>
)}
maxWidth={ACTION_BUTTON_MAX_WIDTH}
to={fileURL}
mb="sp4"
width="100%"
iconName="download"
variant="primary"
aria-label={intl.formatMessage({
defaultMessage: 'Export history button',
id: 'EditDocument.Button.export-file-history.aria-label',
description:
'Aria label for button to download the file history CSV for the document being viewed',
})}
download={`${doc.file.filename}-history.csv`}
/>)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment