如何从打字稿中下载文件(从URL)

问题描述 投票:0回答:1

更新:这个问题曾经问过有关Google Cloud Storage的问题,但后来我意识到,仅尝试将下载内容保存到本地磁盘,该问题实际上是可重现的。因此,我将问题改写为完全与Typescript中的文件下载有关,而不再提及Google Cloud Storage。


[尝试使用WebRequests下载并保存在Typescript中的文件时(尽管我遇到了requestsrequest-promises的相同问题),所有代码似乎都能正确执行,但是生成的文件已损坏并且无法已查看。例如,如果我下载图像,则该文件在任何应用程序中都不可见。

// Seems to work correctly
const download = await WebRequest.get(imageUrl);
// `Buffer.from()` also takes an `encoding` parameter, but it's unclear how to determine the encoding of a download
const imageBuffer = Buffer.from(download.content);
// I *think* this line is straightforward
const imageByteArray = new Uint8Array(imageBuffer);
// Saves a corrupted file
const file = fs.writeFileSync("/path/to/file.png", imageByteArray);

[我怀疑问题出在Buffer.from调用中,无法正确解释下载的内容,但是我不确定如何正确处理。任何帮助将不胜感激。

非常感谢!

node.js typescript file
1个回答
0
投票

根据我在网络请求示例中看到的,download.content只是一个字符串。如果要使用节点SDK将字符串上传到Cloud Storage,则可以使用File.save,直接传递该字符串。

或者,您可以使用here中的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.