使用fs.writeFileSync()JS从GitHub Raw链接本地下载图像



当前正在尝试从GitHub本地下载映像。一切似乎都正常,获取通过200 OK响应,然而,我不知道如何存储图像本身:

const rawGitLink = "https://raw.githubusercontent.com/cardano-foundation/CIPs/master/CIP-0001/CIP_Flow.png" 
const folder = "/Folder"
const imageName = "/Test"
const imageResponse = await axios.get(rawGitLink)

fs.writeFileSync(___dirname + folder + imageName, imageResponse, (err) => {
//Error handling                    
}
)

必须解决四个问题:

  • 在这种情况下,图像名称必须包含png格式
  • 响应必须采用正确的格式作为图像的缓冲区
  • 必须写入响应数据,而不是对象本身
  • __dirname只需要两个下划线
const rawGitLink = "https://raw.githubusercontent.com/cardano-foundation/CIPs/master/CIP-0001/CIP_Flow.png"
const folder = "/Folder"
const imageName = "/Test.png"
const imageResponse = await axios.get(rawGitLink, { responseType: 'arraybuffer' });
fs.writeFileSync(__dirname + folder + imageName, imageResponse.data)
Axios返回一个特殊对象:https://github.com/axios/axios#response-模式
let {data} = await axios.get(...)
await fs.writeFile(filename, data) // you can use fs.promises instead of sync

正如@Leau所说,你应该在文件名中包含扩展名另一个建议是使用path模块创建文件名:

filename = path.join(__dirname, "/Folder", "Test.png")

最新更新