Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
Node JS with Axios. How to get extension of the image from url

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'
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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'];
about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda