javascript - 对于大小超过 ~1MB 的文件,Github.js getSha 出现 403 错误

标签 javascript github github-api http-status-code-403

当我尝试使用 Github.js 时出现 403 错误从大于 ~1MB 的文件中获取 getSha(以及随后的 getBlob)。文件大小有限制吗?代码如下:

var gh = new GitHub({
    username: username,
    password: password
});

// get the repo from github
var repo = gh.getRepo('some-username','name-of-repo');

// get promise
repo.getSha('some-branch', 'some-file.json').then(function(result){

  // pass the sha onto getBlob
  return repo.getBlob(result.data.sha);

}).then(function(result){

  do_something_with_blob(result.data);

});

GitHub API 表示它支持最大 100MB 的 blob,我在 Github.js docs 中找不到任何关于文件大小限制的信息。 .此外,这些文件来自私有(private) Github 存储库。

最佳答案

它抛出一个 403 Forbidden 错误,因为它使用了 Github GET contents API它给出了不超过 1Mo 的文件的结果。例如以下将抛出 403 :

https://api.github.com/repos/bertrandmartel/w230st-osx/contents/CLOVER/tools/Shell64.efi?ref=master

使用 this method使用 GET 树 API,您可以在不下载整个文件的情况下获取文件 sha,然后使用 repo.getBlob(对于不超过 100Mo 的文件使用 Get blob API)。

以下示例将使用 GET 树 api 获取指定文件(对于超过 1Mo 的文件)的父文件夹的树,按名称过滤特定文件,然后请求 blob 数据:

const accessToken = 'YOUR_ACCESS_TOKEN';

const gh = new GitHub({
  token: accessToken
});

const username = 'bertrandmartel';
const repoName = 'w230st-osx';
const branchName = 'master';
const filePath = 'CLOVER/tools/Shell64.efi'

var fileName = filePath.split(/(\\|\/)/g).pop();
var fileParent = filePath.substr(0, filePath.lastIndexOf("/"));

var repo = gh.getRepo(username, repoName);

fetch('https://api.github.com/repos/' +
  username + '/' +
  repoName + '/git/trees/' +
  encodeURI(branchName + ':' + fileParent), {
    headers: {
      "Authorization": "token " + accessToken
    }
  }).then(function(response) {
  return response.json();
}).then(function(content) {
  var file = content.tree.filter(entry => entry.path === fileName);

  if (file.length > 0) {
    console.log("get blob for sha " + file[0].sha);
    //now get the blob
    repo.getBlob(file[0].sha).then(function(response) {
      console.log("response size : " + response.data.length);
    });
  } else {
    console.log("file " + fileName + " not found");
  }
});

关于javascript - 对于大小超过 ~1MB 的文件,Github.js getSha 出现 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849862/

相关文章:

javascript - Sequelize 多对多关系的 Controller

javascript - 在 switch/case 中使用 return 后还需要使用 break 吗?

javascript - 阻止 chrome 在我的扩展中启动时加载所有选项卡?

javascript - 如果分配了多个类,如何检查类名?

git - 首次访问后 FluxCD 失败

javascript - 验证我的 Angular 应用程序以便在 github 存储库上获得协作者

javascript - 开源版本的 Git API

混帐包 : two-way all branches sync between local and remote repo

github - github api v3可以从master以外的特定分支获取文件内容

github - 使用 GitHub GraphQL API v4 查询单个存储库中的所有提交