I tried to create a serializer for an asset of type file that is part of a PortableText field, in order to display a download link for the file. This is what works for me,...

1 replies
Last updated: Nov 25, 2020

I tried to create a serializer for an asset of type file that is part of a PortableText field, in order to display a download link for the file. This is what works for me, not sure if there are better options, but I couldn’t find a GraphQL way of getting the asset->url (that would have been the GROQ way) into my GatsbyJS site:

import React from 'react'
import css from './downloadableFile.module.scss'

export default ({ node }) => {
  const baseURL = '<https://cdn.sanity.io/files/>'
  const fileName = `${node.file.asset._ref.split('-')[1]}.${node.file.asset._ref.split('-')[2]}`
  const downloadURL = `${baseURL}${process.env.SANITY_PROJECT_ID}/${process.env.SANITY_DATASET}/${fileName}?dl`

  return (
    &lt;div className={css.root}&gt;
      &lt;p&gt;{node.title} &lt;a href={`${downloadURL}`}&gt;Download&lt;/a&gt;&lt;/p&gt;
    &lt;/div&gt;
  )
}
Just in case this helps anyone.

Nov 25, 2020, 10:43 AM

If you’re using a raw field you could consider using resolveReferences. See example in this section https://github.com/sanity-io/gatsby-source-sanity/#raw-fields
You don’t get the same level of control over which references are resolved as with GROQ but it’s a useful option.

Nov 25, 2020, 10:48 AM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.