How to preserve image filename when using fields in Sanity query?
When you add custom fields to an image type in Sanity, the Studio stops displaying the default filename and shows "Untitled" instead. This happens because adding fields changes how the preview is configured. The solution is to add a preview configuration to your image type that explicitly selects the filename.
The key is to place the preview configuration on the image object itself, not on the array that contains it. Here's how to fix it:
{
name: 'assetFiles',
type: 'array',
title: 'Files',
of: [
{
type: 'image',
fields: [
{
name: 'caption',
type: 'string',
title: 'Caption',
},
{
name: 'alt',
type: 'string',
title: 'Alt Text',
}
],
preview: {
select: {
title: 'asset.originalFilename',
media: 'asset'
}
}
}
]
}The important parts here are:
title: 'asset.originalFilename'- This tells Sanity to use the original filename from the asset as the title in the previewmedia: 'asset'- This ensures the image thumbnail still displays alongside the filename- Location matters - The
previewblock must be inside the image object definition (after thefieldsarray), not on the parent array
The asset.originalFilename property is automatically set by Sanity when you upload an image, so you don't need to create any additional fields. Other useful asset properties you could use include asset.url or any other metadata fields available on the asset.
If you want to get fancy, you can also use the prepare function to customize the display further:
preview: {
select: {
title: 'asset.originalFilename',
media: 'asset',
caption: 'caption'
},
prepare({title, media, caption}) {
return {
title: title || 'Untitled',
subtitle: caption,
media: media
}
}
}This approach gives you back the filename display while maintaining your custom fields for captions, alt text, or any other metadata you need to store with your images.
Show original thread10 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.