【问题标题】:YouTubeAPI: How to upload thumbnail (JS)YouTube API:如何上传缩略图 (JS)
【发布时间】:2021-06-13 20:40:32
【问题描述】:

我尝试使用本指南在 youtube 上上传缩略图:https://developers.google.com/youtube/v3/docs/thumbnails/set

我能够使用这个 curl 在邮递员上成功运行它:

curl --location --request POST 'https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=<video id>' \
--header 'Authorization: OAuth <token>' \
--header 'Content-Type: image/png' \
--form 'thumbnail=@"/C:/Users/user/Pictures/nami.PNG"'

但是我在将其翻译成 js 时遇到了麻烦,到目前为止我所做的是:

// the "file" is the File from <input type="file"> - data on this looks ok
uploadThumbnail async (file) {
   const formData = new FromData();
   const formData.append('thumbnail', file, 'test.png');


   await fetch.post('https://www.googleapis.com/youtube/v3/thumbnails/set', {
     headers: {
        Authorization: 'Oauth <token>',
        'Content-Type': 'multipart/form-data' // I also tried using the file.type here (image/png)
     },
     query: {
       videoId: <video id>
     },
     body: formData,
   })
}

(为了简化逻辑,上面的代码我只是手动打出来的,如有错别字请见谅)

但这会抛出The request does not include the image content.我不明白,我也尝试将文件转换为Blob,但同样的错误。

【问题讨论】:

  • 授权:承载
  • 即使它确实有效,上面的 curl 命令也不属于 YouTube 数据 API 的记录行为。 proper curl 命令可以在我最近在这个论坛上提供的答案中看到:Upload thumbnail to Youtube API using curl
  • 从引用的答案中,您可以很容易地得出对 Thumbnails.set 端点的正确 JS 调用。
  • @stvar 是哪一个?
  • 您还可以阅读以下答案以了解如何使用 JS 的fetch API 上传文件:How do I upload a file with the JS fetch API?

标签: javascript curl youtube-api fetch youtube-data-api


【解决方案1】:

正如我在主要帖子中的 cmets 中指出的那样,我结合了答案并想出了这个(这行得通!)

   await fetch.post(`https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=${videoId}&uploadType=media`, {
     headers: {
        Authorization: 'Bearer <token>',
        'Content-Type': file.type
     },
     body: file,
   })

错误是:

  • 我的端点错误并且缺少 uploads(此 API 与其他 youtube 端点不同,因此如果您要重用变量 base_url,最好检查一下。
  • 使用Oauth 代替Bearer
  • 提取中没有query
  • formData无需转换添加,直接传文件即可。

【讨论】:

  • 请注意,调用 URL应该包含参数uploadType=media。没有它,它可能现在工作;但是,根据规范进行编码始终是一种好习惯。 (例如 Google 的官方公共代码:discovery.py;不幸的是,我无法向您提供官方 JS 代码,因为 Google 的 GAPI 不是开源的。)
  • @stvar 我不知道这个(并且不在文档中)感谢您提供的信息!干杯!
  • 确实official endpoint docs 不像官方源代码那样明确。这个问题。不幸的是,现在我无法向您指出指定该请求参数的官方文档(而不是官方代码),但我会查找它。无论如何,请更新您上面的答案,以便对您的答案感兴趣的其他 SO 用户使用 符合规范的 URL
  • 这是一个 official page,它是 Google Drive API 的一部分;请求参数 uploadType 已详细记录,包括其 media 值。
  • 您可能会质疑这句话是否与 YouTube Data API 相关;但是,请考虑 Google 实现的 REST 机制(包括将文件上传到 Google Drive 或将缩略图上传到 YouTube)用于一整套不同的 API,乍一看可能看起来不相关。
猜你喜欢
  • 2013-08-25
  • 2020-12-30
  • 2015-08-11
  • 2021-10-07
  • 2021-05-21
  • 1970-01-01
  • 2013-07-15
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多