【问题标题】:Download a file without file ending nodejs下载没有文件结尾nodejs的文件
【发布时间】:2021-07-28 20:15:09
【问题描述】:

例如:https://preview.redd.it/04o5k2n06zd71.jpg?width=960&crop=smart&auto=webp&s=7baa25e7e1bde3436cb2a265e2fc8c6cb9a758ee

如何将该图像下载/加载到缓冲区

注意: 结局总是可以不同的。

【问题讨论】:

  • “没有文件结尾的nodejs”是什么意思?
  • 在 nodejs 中,任何 http 请求库 here 都适用于发出 http 请求并获得响应。我个人最喜欢的是got(),但该列表中的所有内容都很好。

标签: node.js image download


【解决方案1】:

这是一个使用 got() 库的 nodejs 实现:

const got = require('got');

const url =
    'https://preview.redd.it/04o5k2n06zd71.jpg?width=960&crop=smart&auto=webp&s=7baa25e7e1bde3436cb2a265e2fc8c6cb9a758ee';

got(url, { responseType: 'buffer' }).then(result => {
    // result.body contains a Buffer object with the image in it
    console.log(`content-type: ${result.headers['content-type']}`);
    console.log(`isBuffer: ${Buffer.isBuffer(result.body)}`);
    console.log(result.body);
}).catch(err => {
    console.log(err);
});

您可以直接使用 nodejs 运行此代码(在安装 got() 库之后)。当我运行它时,它会生成以下输出:

content-type: image/jpeg
isBuffer: true
<Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 1c 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 0c 6c 63 6d 73 02 10 00 00 ... 89335 more bytes>

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多