【问题标题】:Image download via node request module is corrupt通过节点请求模块下载的图像已损坏
【发布时间】:2023-03-29 14:51:01
【问题描述】:

我正在尝试通过 npm request module 下载图像,并使用 fs.writeFile 保存,但是文件在保存到磁盘时已损坏,已使用 imagemagick identify 命令进行验证。

const fs = require('fs');
const path = require('path');
const request = require('request');

const brandLogoUrl  = 'https://example.net/logo.png';
const filename      = path.basename(brandLogoUrl);
const brandLogoPath = `./${filename}`;

request(brandLogoUrl, (error, rsp, body) =>  {
        fs.writeFile(brandLogoPath, body, 'binary', (err) => {
            console.log('brand logo saved');
        });
    });
});

当我用identify检查保存的文件时,结果:

识别:不正确的图像标题 `logo.png' @ 错误/png.c/ReadPNGImage/3940.

但是,如果我通过 wget 下载相同的 URL 并使用 identify 检查它,结果是

logo.png PNG 283x109 283x109+0+0 8 位 sRGB 19KB 0.000u 0:00.000

JS 看起来很简单,但似乎有些东西我忽略了。你能看出来吗?

编辑

我尝试了 https 模块(基于this post),它可以工作

var fs = require('fs');
var https = require('https');
//Node.js Function to save image from External URL.
var url = 'https://example.net/logo.png';
var file = fs.createWriteStream('./logo.png');
https.get(url, function(response) {
    response.pipe(file);
});

【问题讨论】:

    标签: node.js image request filesystems


    【解决方案1】:

    您缺少的是响应的编码。当您使用此库发出请求时,默认情况下它被编码为字符串 (utf-8)。根据documentation of the request module,您必须通过encoding: null 才能正确获取二进制数据。

    所以你的代码应该是这样的:

    request({ url: brandLogoUrl, encoding: null }, (error, rsp, body) =>  {
      fs.writeFile(brandLogoPath, body, 'binary', (err) => {
        console.log('brand logo saved');
      });
    });
    

    这也是https 模块运行良好的原因——它只是传递未经任何编码的原始数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2020-08-08
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多