How to access filename of file object in Sanity preview for list view?
To access the filename of a file asset in your preview, you need to use the select property with dot notation to reach into the nested asset object. The filename is stored at asset.originalFilename.
Here's how to configure your preview:
const pdf: IObjectType = {
name: 'pdf',
title: 'PDF',
type: 'file',
description: 'Upload PDF files.',
fields: [
{
name: 'title',
title: 'Descriptive Name for PDF in Download Card',
type: 'string',
validation: (Rule: IRuleType): IRuleType => Rule.required(),
},
],
preview: {
select: {
title: 'title',
filename: 'asset.originalFilename' // Access the filename from the asset
},
prepare({title, filename}) {
return {
title: title || filename, // Use title if available, otherwise filename
subtitle: filename // Show filename as subtitle
}
}
}
}The key is understanding that file type fields in Sanity store a reference to an asset object, and that asset has properties like originalFilename, size, extension, etc. You can access these nested properties in the select object using dot notation.
If you want to show additional file information, you can select multiple asset properties:
preview: {
select: {
title: 'title',
filename: 'asset.originalFilename',
extension: 'asset.extension',
size: 'asset.size'
},
prepare({title, filename, extension, size}) {
return {
title: title || filename,
subtitle: `${filename} (${extension?.toUpperCase()}) - ${(size / 1024).toFixed(2)} KB`
}
}
}This works because the preview configuration system allows you to use dot notation to access nested fields and referenced documents. The same pattern works for accessing fields from referenced documents (like author.name) or nested objects (like asset.originalFilename).
Show original thread2 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.