Node.js get file extension

后端 未结 13 978
后悔当初
后悔当初 2020-12-23 00:16

Im creating a file upload function in node.js with express 3.

I would like to grab the file extension of the image. so i can rename the file and then append the file

13条回答
  •  情歌与酒
    2020-12-23 00:45

    I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)

    Assume you are sending your data using HTTP POST:

    POST /upload2 HTTP/1.1
    Host: localhost:7098
    Connection: keep-alive
    Content-Length: 1047799
    Accept: */*
    Origin: http://localhost:63342
    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/51.0.2704.106 Safari/537.36
    Content-Type: multipart/form-data; boundary=----   WebKitFormBoundaryPDULZN8DYK3VppPp
    Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
    Accept-Encoding: gzip, deflate
    Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
    Request Payload
    ------WebKitFormBoundaryPDULZN8DYK3VppPp
    Content-Disposition: form-data; name="image"; filename="blob"
    Content-Type: image/png
    
    
    ------WebKitFormBoundaryPDULZN8DYK3VppPp--
    

    Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).

    Restify BodyParser converts this header in to a property with name type

    File {
      domain: 
       Domain {
         domain: null,
         _events: { .... },
         _eventsCount: 1,
         _maxListeners: undefined,
         members: [ ... ] },
      _events: {},
      _eventsCount: 0,
      _maxListeners: undefined,
      size: 1047621,
      path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
      name: 'blob',
      **type: 'image/png'**,
      hash: null,
      lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
      _writeStream: 
      WriteStream {
       ... },
         writable: true,
         domain: 
         Domain {
            ...
         },
          _events: {},
          _eventsCount: 0,
         _maxListeners: undefined,
         path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
         fd: null,
         flags: 'w',
         mode: 438,
         start: undefined,
         pos: undefined,
         bytesWritten: 1047621,
         closed: true } 
    }
    

    You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search

    • mime
    • mime-types

    and their usage is simple as well:

     app.post('/upload2', function (req, res) {
      console.log(mime.extension(req.files.image.type));
     }
    

    above snippet will print png to console.

提交回复
热议问题