Check if the given URL is an image

Asked

Viewed 112 times

1

I am making an application in Node.js, and I want to make a system of custom backgrounds using the URL given by the user, I would like to know how to check if the URL given by the user is an image, and if it is not, the application gives return.

1 answer

3

You can use the file-type:

npm install file-type

Sample code:

const http = require('http');
const fileType = require('file-type');
const url = 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png';

http.get(url, res => {
    res.once('data', chunk => {
        res.destroy();
        console.log(fileType(chunk));
    });
});

Upshot:
{ ext: 'png', mime: 'image/png' }

A way to check whether the url contains the image in the format you want:

if (!(fileType(chunk).ext == "png")) {
    console.log("deu ruim");
    // aqui vem o seu return
}

Example taken from here.

  • I had never heard of this package, but as I will do the system in which case the URL is not an image the app gives return?

  • You will compare the result of fileType(chunk) with the formats you want to accept (png, jpg, etc.) instead of sending to the console - if it is false, you give your return - what you think?

  • @Gabriel Includes at the end of the answer a comparison with a type of extension.

  • if (!(filetype(Chunk).ext == "png")) { Typeerror: Cannot read Property 'ext' of null

  • 1

    @Gabriel Tried with the url I put of example?

  • yes, then it worked, then I changed the URL to see if the Return code worked, and gave this.

  • @Gabriel it might be interesting for you to open a new question by placing the code and error you are having - pq. I think you’ll change this question too much if you edit.

  • https://answall.com/questions/211351/erro-ao-usar-o-file-type

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.