node.js - 使用 fs.writeFile 保存图像

标签 node.js image axios fs

我正在尝试使用从 https://picsum.photos/ 获得的 Node 文件系统来保存图像但正在写入的文件不是我所期望的。

const axios = require('axios');
const path = require('path');
const fs = require('file-system');

axios.get('https://picsum.photos/id/237/200/300')
  .then((data) => {
    fs.writeFile(path.resolve(__dirname, '../assets/test/test1.jpg'), data.data, (err) => {
      if (err) {
        console.log(err);
        throw err;
      }
      console.log('file save successfully');
    });
  })
  .catch((err) => {
    console.log(err);
  });

This is what the file results as

最佳答案

数据可能以错误的编码返回,因为没有指定编码 - 最有可能是文本而不是二进制流,因为 responseType'json' 默认情况下。 docs 上有一个使用 axios 请求将图像写入磁盘的示例。 ,其中 responseType 设置为 stream 并且给定的流通过管道传输到 writeStream。这可能就是您需要的方法。

下面是文档中给出的代码示例:

// GET request for remote image
axios({
  method: 'get',
  url: 'https://picsum.photos/id/237/200/300',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

如果您仍想使用writeFile,则可以设置responseType: 'arraybuffer',并将给定的缓冲区传递给fs.writeFile >.

关于node.js - 使用 fs.writeFile 保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60677305/

相关文章:

html - 为什么以及如何将图像保存在一张图像中?

php - 使用 php 从 html 生成图像

java - 在Java中更改png的非透明部分的颜色

javascript - 公理 : How exactly to preserve session after successful authorization and send with subsequent request - while testing without browser

reactjs - 无法使用 axios 和 ReactJS 执行获取请求

node.js - 使用 buildpacks 在 heroku 上执行和 PATH

node.js - 为什么 “npm install” 不重写 package-lock.json?如果不存在也不生成新的?

javascript - 尽管存在快速路由,但 Axios 在 POST 请求上抛出 404 错误

javascript - 在同步函数中从 AWS Lambda 发出 AWS CloudWatch 指标

node.js - 使用 jasmine 和 node.js 模拟文件系统