提问者:小点点

使用Node.js在本地文件系统中保存图像


我正在编写一个简单的代码,从一个网站下载丢失的图像,并将其保存在本地系统中,给定其完整的URL。 我能够得到二进制格式的数据作为响应,而且我能够正确地保存它。 但当我试图打开图像时,它显示系统不支持该格式。 我试图保存一些js和css文件,它们被正确保存,我也能够查看它们。 但我对所有的图像格式都有问题。 下面是我写的代码:

try {
  response = await axios.get(domain + pathOfFile);
  console.log(response);
  fs.writeFile(localBasePath + pathOfFile, response.data, "binary", (error) => {
    if (error) console.log("error while writting file", error.message);
  });
} catch (error) {
  console.log("error in getting response", error.message);
}

domian:包含站点的基域
PathofFile:包含该域上文件的路径
LocalBasePath:需要存储映像的基文件夹
我甚至尝试将响应存储在缓冲区中,然后尝试保存映像,但仍然面临同样的问题。 如有任何建议,将不胜感激。


共1个答案

匿名用户

您需要在调用Axios.get方法时定义ResponseEncoding

将您的行更改为:

response = await axios.get(domain + pathOfFile, {responseEncoding: "binary"});