我想知道是否可以通过 HTTP 请求从 Sanity 下载文件?
我只有参考 ID:
{
file: {
asset: {
_ref: "file-fxxxxxxxxxxxxxxxxxxxx-xlsx"
_type: "reference"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想做的是这样的场景:
<a href="https://cdn.sanity.io/assets/clientID/dataset/file-xxxxxxxxxxx-xlsx">
Download File
</a>
Run Code Online (Sandbox Code Playgroud)
小智 12
事实上,您可以通过一些自定义代码,只需从_ref文件文档的_id
_ref/创建 URL_id_ref/结构_id是这样的:(file-{ID}-{EXTENSION}例如file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3:)。
这样,您就可以生成可下载的 URL,其结构如下:https://cdn.sanity.io/files/{PROJECT_ID}/{DATASET}/{ID_OF_FILE}.{EXTENSION}。以下是该操作的一些伪 Javascript 代码:
const getUrlFromId = ref => {
// Example ref: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3
// We don't need the first part, unless we're using the same function for files and images
const [_file, id, extension] = ref.split('-');
return `https://cdn.sanity.io/files/${PROJECT_ID}/${DATASET}/${id}.${extension}`
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您可以使用GROQ查询文件的文档,那就更容易了:
*[(YOUR FILTER HERE)] {
file->{ url } // gets the URL from the referenced file
}
Run Code Online (Sandbox Code Playgroud)
您也可以对图像执行相同的操作。