Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to render and download a file type in Sanity.io

17 replies
Last updated: May 19, 2022
How to I render a File type that is downloadable
May 19, 2022, 7:58 AM
You’ll need to use a file type as part of your schema. This will enable you to upload documents, such as PDFs in your studio. Then you can get their upload URL in your queries, and create a download feature on your frontend (typically a
<a>
element with the
download
attribute would do).
May 19, 2022, 8:02 AM
I have this as a type
{
            name: "installatiesheet",
            title: "Installatiesheet",
            type: "file",
        },
this works and I can upload a file in sanity studio. But what does the snippet look like to render it as

<a>
May 19, 2022, 8:04 AM
Well, you’ll need to query that data in your query first.
"url": installatiesheet -> url
And then once you have the URL in he frontend, you can do something like:

<a href={url} download>Download</a>
May 19, 2022, 8:05 AM
FYI: the
download
attribute does not work, if the file url has a different origin as the website. See https://html.spec.whatwg.org/multipage/links.html#downloading-resources
That is the case for all files uploaded to Sanity Content Lake.
May 19, 2022, 8:08 AM
There are workarounds for this, like using a server-less api request to proxy the file to the client, but I wouldn’t recommend it.
May 19, 2022, 8:10 AM
Ah yes, you’re right. In that case, using the
?dl
attribute from Sanity asset pipeline is the way to go I guess: https://www.sanity.io/docs/image-urls#dl-9836df902327
May 19, 2022, 8:10 AM
Uhhh, nice! I didn’t knew about this attribute. Thanks!
May 19, 2022, 8:11 AM
hmm interesting, how do i use the
dl
attribute?
May 19, 2022, 8:14 AM
You would pass it as part of the URL to the document, as mentioned in the documentation.
May 19, 2022, 8:14 AM
and how do I fetch the quiry url of that file type?
May 19, 2022, 8:15 AM
I showed you above. :)
May 19, 2022, 8:19 AM
sorry I'm not that bright hahaha I'm not geting this to work do you have a example for how to use that in
return (
)
and do i need to change something in the content type ?
May 19, 2022, 8:25 AM
I mean, I can’t give you much more than what I already shared in that thread. You will need to query the URL to your file as shown in one of my message earlier in this thread, and then you pass that URL to your
<a>
anchor.
May 19, 2022, 8:26 AM
Can I render the PDF document as Iframe instead by download?
May 19, 2022, 8:30 AM
May 19, 2022, 8:35 AM
Thanks
May 19, 2022, 8:37 AM
Thanks alot guys I got it working
May 19, 2022, 8:44 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?