Home > Back-end >  Node JS with Axios. How to get extension of the image from url
Node JS with Axios. How to get extension of the image from url

Time:12-07

I am trying to download the image and save it in my server from the url address. So for example I make a POST request with URL of the image. I download the image and I save it in my server. The problem comes when I need to figure our the extension of the image. Right now it works staticaly only for jpg files, but it should work for png aswell. How can I find out the extension of the file before saving it?

One way would be to get the extension from the url itself, but not all urls will have the extension , for example: https://media.istockphoto.com/photos/winter-in-the-sequoias-picture-id1292624259

This is the code that I have made right now. It works, however how I said, its static and only working for 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'
}

CodePudding user response:

You can use response headers for that. The Content-Type header should tell you the type of the file and with Content-Disposition you can get the filename with extension.

In your code you can access these headers like this

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

CodePudding user response:

I'd suggest using a module such as mime to get the extension from the content-type.

Complete example:

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)

This will give an output somewhat like:

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