πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Importing block content with images into Sanity and resolving issues.

5 replies
Last updated: Aug 9, 2023
Hey there everyone,
I'm curious if anyone can offer some guidance on importing block content that contains images. I have already used the
@sanity/block-tools
to import the content, but would like all images to also be imported into Sanity as well.
I have already been using the
_sanityAsset
helper elsewhere, but I'm not certain how to format the rules so that Sanity gets the structure correct. Some pointers would be very appreciated!
Jun 12, 2023, 10:17 PM
After some experimenting, this does the trick:

'rules': [
  {
    deserialize(el, next, block) {
      if (el.tagName?.toLowerCase() === 'img') {
        return block({
          _type: 'image',
          _sanityAsset: `image@${el.src}`,
          nodes: next(el.childNodes),
        })
      }
    }
  }
]
Jun 12, 2023, 10:32 PM
Thanks for sharing your solution!
Jun 12, 2023, 11:04 PM
user S
When you did this, did you load the images to Sanity beforehand?
Jul 29, 2023, 8:25 PM
user S
actually I'm curious of your whole blockContent structure. Really struggling to get images to load.
Jul 31, 2023, 5:34 PM
user S
The schema for the block content is something like this:



{
  type: 'array',
  name: 'content',
  title: 'Content',
  description: 'The content of the blog post.',
  of: [
    {
      type: 'block',
    },
    {
      type: 'image',
      fields: [
        {
          type: 'string',
          name: 'alt',
          title: 'Alt',
          description: 'The alt text of the image',
        },

      ],
    },
  ],
},
The query includes something like this:


content[] {
  ...,
  _type == "image" => {
    "src": asset->url,
    alt,
  },
},
And then the import script basically ran a rule like I pasted in my original post which was deserializing images from source HTML files and replacing them with "sanity images". That would then get output to a ndjson file, and imported using the CLI.

Note that the `_sanityAsset: `image@${el.src}`` line basically tells sanity to load whatever is at
el.src
as an image during the import.
Would be helpful to know if: you're still seeing issues, and if you are, where specifically you're seeing them. ie, importing them? querying them? Displaying them?
Aug 9, 2023, 12:50 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?