使用 GitHub API 下载文件时解码 base64 [英] Decoding base64 while using GitHub API to Download a File

查看:20
本文介绍了使用 GitHub API 下载文件时解码 base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am using the GitHub API to download a file from GitHub. I have been able to successfully authenticate as well as get a response from github, and see a base64 encoded string representing the file contents.

Unfortunately, I get an unusual error (string length is not a multiple of 4) when decoding the base64 string.

The HTTP request is illustrated below:

GET /repos/:owner/:repo/contents/:path

The (partial) response is illustrated below:

{
    "name":....,
    "download_url":...",
    "type":"file",
    "content":"ewogICAgInN3YWdnZXIiOiAiM...
}

The issue I am encountering is that the length of the string is 15263 bytes, and I get an error in decoding the string (string length is not a multiple of 4). I am using node.js and the 'base64-js' npm module to decode the string. Code to execute the decoding is illustrated below:

var base64 = require('base64-js');
var contents = base64.toByteArray(fileContent);

The decoding causes an exception:

Error: Invalid string. Length must be a multiple of 4
    at placeHoldersCount (.../node_modules/base64-js/index.js:23:11)
    at Object.toByteArray (...node_modules/base64-js/index.js:42:18)
    :
    :

I would think that the GitHub API is sending me the correct data, so I figure that is not the issue.

Am I performing the decoding improperly or is there another problem I am overlooking?

Any help is appreciated.

解决方案

I experimented a bit and found a solution by using a different base64 decoding library as follows:

var base64 = require('js-base64').Base64;
var contents = base64.decode(res.content);

I am not sure if it is mandatory to have an encoded string length divisible by 4 (clearly my 15263 character length string is not divisible by 4) but the alternate library decoded the string properly.

A second solution which I also found to work is specific to how to use the GitHub API. By adding the following to the GitHub API call header, I was also able to get the decoded file contents:

'accept': 'application/vnd.github.VERSION.raw'

这篇关于使用 GitHub API 下载文件时解码 base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆