Search code examples
node.jsimagemime

how to find MIME type of a image which has no extension?


I am using Node.js server, and am saving images onto server with no file extension, (image name is just a number) is there any way to find out the MIME type of this kind of images? i need it as the browser is downloading the image instead of opening it in the browser.

I am using gm(GraphicsMagick) package to write text onto a image and am saving it into a folder without extensions. when i send this path via res.sendFile('project root/uploads/cache/1') , the browser doesn't understand its a image and downloads it, i want it to open it in the same tab

i also tried setting image/* , the browser just downloads the image, i am not sure if this kind of API can be consumed on React-Native app without problems.


Solution

  • Assuming you use multer as your file uploading middleware:

    Router.js

    multer  = require('multer'),
    
    storage = multer.diskStorage({
        // Configuring multer to upload towards the public/uploads map
        destination: function(req, file, cb) {
            cb(null, 'public/uploads')
        },
        // Rename the file, so we can create a reference to save in the database.
        filename: function(req, file, cb) {
            var ext = file.originalname.split('.')
            cb(null, 'upload-' + Date.now() + '.' + ext[ext.length - 1])
      }
    
    })  
    
    // Assign the configured storage to the upload.
    upload = multer({ 
        storage: storage,
    })
    

    I configure my storage to rename all images (as multer does by default) into upload - Date.now() and the extension in the ext array. This way, the file gets saved with the extension, and automatically gives the following result:

    Example how it looks when uploaded