繁体   English   中英

带有 Axios 的节点 JS。 如何从 url 获取图像的扩展

[英]Node JS with Axios. How to get extension of the image from url

我正在尝试从 url 地址下载图像并将其保存在我的服务器中。 例如,我使用图像的 URL 发出 POST 请求。 我下载图像并将其保存在我的服务器中。 当我需要计算图像的扩展时,问题就来了。 现在它仅适用于 jpg 文件,但它也适用于 png 文件。 如何在保存之前找出文件的扩展名?

一种方法是从 url 本身获取扩展名,但并非所有网址都有扩展名,例如: https://media.istockphoto.com/photos/winter-in-the-sequoias-picture-id129262425

这是我现在制作的代码。 它可以工作,但是我怎么说,它的 static 仅适用于 jpg:

var config = {
    responseType: 'stream'
};

async function getImage(url) {

    let time = Math.floor(Date.now() / 1000)
    let resp = await axios.get(url, config)
    resp.data.pipe(fs.createWriteStream(time+'.jpg')) // here I need to get the image extension isntead of static '.jpg'
}

您可以为此使用响应标头。 Content-Type header 应该告诉您文件的类型,使用Content-Disposition您可以获得带有扩展名的文件名。

在您的代码中,您可以像这样访问这些标头

resp.headers['content-type'];
resp.headers['content-disposition'];

我建议使用诸如mime之类的模块从内容类型中获取扩展名。

完整示例:

const axios = require('axios');
const fs = require('fs');
const mime = require('mime');

var config = {
    responseType: 'stream'
};

async function getImage(url) {

    let time = Math.floor(Date.now() / 1000)
    let resp = await axios.get(url, config)

    const contentLength = resp.headers['content-length'];
    const contentType = resp.headers['content-type'];
    const extension = mime.extension(contentType);
    
    console.log(`Content type: ${contentType}`);
    console.log(`Extension: ${extension}`);
    const fileName = time + "." + extension;

    console.log(`Writing ${contentLength} bytes to file ${fileName}`);
    resp.data.pipe(fs.createWriteStream(fileName));
}

const url = 'https://media.istockphoto.com/photos/winter-in-the-sequoias-picture-id1292624259';
getImage(url)

这将使 output 有点像:

Content type: image/jpeg
Extension: jpeg
Writing 544353 bytes to file 1638867349.jpeg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM