【问题标题】:How to download file from Sanity via HTTP?如何通过 HTTP 从 Sanity 下载文件?
【发布时间】:2021-01-29 00:50:56
【问题描述】:

我想知道是否可以通过 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


    【解决方案1】:

    确实可以 ? 只需使用一些自定义代码,您就可以从文件文档的_ref(文件文档的_id)中完成此操作

    从文件的_ref/_id 创建 URL

    _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
    }
    

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

    【讨论】:

    • 对.. 一段时间后我想通了。非常感谢
    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 2010-12-25
    • 2015-07-07
    相关资源
    最近更新 更多