How to get image URLs from array field and enable multi-image upload in Sanity?
Welcome to Sanity! Great questions - these are common when starting out with arrays of images. Let me help you with both issues.
Getting URLs from an Array of Images
The issue with your GROQ query is that you need to add [] to traverse the array. Here's the corrected query:
ProjectImages[] {
asset-> {
_id,
url
}
}The [] tells GROQ to iterate through each item in the array and fetch the asset information for each image.
Even better approach: You can use the @sanity/image-url package to generate URLs directly from the asset reference without having to expand the asset document in your query. This is the recommended approach as it gives you more control over image transformations (size, format, quality, etc.).
Here's how to set it up:
import imageUrlBuilder from '@sanity/image-url'
import { client } from './client'
const builder = imageUrlBuilder(client)
function urlFor(source) {
return builder.image(source).url()
}
// Then use it with your images:
ProjectImages.forEach(image => {
const url = urlFor(image)
console.log(url)
})Enabling Multi-Select for Image Upload
Good news! Sanity already supports this - you just need to drag and drop multiple files onto the array field. Select multiple image files from your file explorer and drag them all at once onto the array input in the Studio, and they'll all be uploaded together.
The UX could be clearer (and the Sanity team is aware of this), but the functionality is there. Unfortunately, there isn't currently a way to use the file picker dialog to select multiple files at once - drag-and-drop is the way to go for now.
Bonus: Adding Captions to Individual Images
If you want to add captions or other metadata to each image in your array, you can add custom fields like this:
{
name: 'ProjectImages',
title: 'Project Images',
type: 'array',
of: [{
type: 'image',
fields: [
{
name: 'caption',
type: 'string',
title: 'Caption',
options: {
isHighlighted: true // Makes it easily accessible
}
}
]
}]
}Then query it like:
ProjectImages[] {
caption,
asset-> {
url
}
}Hope this helps! Let me know if you have any other questions.
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.