首页 > 解决方案 > 如何通过 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>

标签: sanity

解决方案


您确实可以使用一些自定义代码,您可以从_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
}

你也可以对图像做同样的事情。


推荐阅读