How to determine if a given URL link is a video or image?

后端 未结 6 1215
遥遥无期
遥遥无期 2021-01-18 15:06

I\'m trying to take a given URL entered by user and determine if the URL is pointing to a image or a video.

Example use case:

When a user paste in the URL o

6条回答
  •  庸人自扰
    2021-01-18 15:25

    I suggest using curl with a range header to allow you to inspect the file type itself.

    curl -s -v -r0-499 -o test  http://stackoverflow.com/content/img/so/logo.png
    * About to connect() to stackoverflow.com port 80 (#0)
    *   Trying 69.59.196.211... connected
    * Connected to stackoverflow.com (69.59.196.211) port 80 (#0)
    > GET /content/img/so/logo.png HTTP/1.1
    > Range: bytes=0-499
    > User-Agent: curl/7.19.4 (i386-apple-darwin9.6.0) libcurl/7.19.4 zlib/1.2.3
    > Host: stackoverflow.com
    > Accept: */*
    > 
    < HTTP/1.1 206 Partial Content
    < Cache-Control: max-age=604800
    < Content-Type: image/png
    < Content-Range: bytes 0-499/3438
    < Last-Modified: Fri, 05 Jun 2009 06:52:35 GMT
    < Accept-Ranges: bytes
    < ETag: "25dd4b35aae5c91:0"
    < Server: Microsoft-IIS/7.0
    < Date: Fri, 19 Jun 2009 19:39:43 GMT
    < Content-Length: 500
    < 
    { [data not shown]
    * Connection #0 to host stackoverflow.com left intact
    * Closing connection #0
    

    Then execute:

    $ file test
    test: PNG image data, 250 x 61, 8-bit colormap, non-interlaced
    

    Now you know the mime type: image/png, the file size 3438 bytes, and the file is a 250 x 61 color PNG image.

提交回复
热议问题