sanity - 如何通过 HTTP 从 Sanity 下载文件?
问题描述
我想知道是否有可能通过 HTTP 请求从 Sanity 下载文件?
我只有参考 ID:
{
file: {
asset: {
_ref: "file-fxxxxxxxxxxxxxxxxxxxx-xlsx"
_type: "reference"
}
}
}
我想这样做是这种情况:
<a href="https://cdn.sanity.io/assets/clientID/dataset/file-xxxxxxxxxxx-xlsx">
Download File
</a>
解决方案
您确实可以使用一些自定义代码,您可以从_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}`
}
直接查询网址
但是,如果您可以使用GROQ查询文件的文档会更容易:
*[(YOUR FILTER HERE)] {
file->{ url } // gets the URL from the referenced file
}
你也可以对图像做同样的事情。
推荐阅读
- html - 如何排除css中的特定类?
- javascript - Internet Explorer 中的 Javascript 无效字符错误,但不是 Google Chrome
- c++ - gcc 和 clang 在表达式是否是常量评估上存在分歧
- ansible - Ansible:如何获取任务名称作为变量
- python - 在 django 中从数据库中打开特定的 pdf 文件
- postgresql - Postgresql:使用不同的参数多次重复查询 - 比联合更清洁的方法?
- python-3.x - OSError:[E050] 找不到模型“de”。它似乎不是快捷链接、Python 包或数据目录的有效路径
- python - 如何在熊猫中设置日期时间地板操作的基础?
- java - 与选择混淆(浮点数)
- spring-kafka - 为什么异步生产者正在生成 linger.ms 和 batch.size 设置为较大值且 autoFlush 设置为 false 的消息?