DEV Community

abhigsri
abhigsri

Posted on

Image file/files upload with multer, node and express

A simple and complete file upload without the intervention of html file type

Hey guys just wanted to share with you the stuff on which I have been working on recently.
I have been trying to upload an image with node server and get it done with multer.
I know that it is quite easy as it is available with all the details when you search this on Google.

So why I am writing this postπŸ€”
As I had a requirement in which an image or more than one image needed to download from other server and then needed to upload it all on node server which does not have the intervention of html form and file type, So the solution for the given scenario is as given below.

Client

var data;
var xhr = new XMLHttpRequest();
var imgUri = "https://cors-anywhere.herokuapp.com/https://nodejs.org/static/images/logos/nodejs-new-pantone-black.png";  // your image url which you needed to download first
xhr.open("GET", imgUri);
xhr.responseType = "blob";  // just make sure you get the blob type in response
xhr.onload = function() {
  data = xhr.response;
  uploadImage(data);
}
xhr.send();

function uploadImage(blobImg) {
  // console.log(blobImg);

  var imgData = new FormData();  // create a new form data
  imgData.append("image", blobImg, "node_icon.png");

  // append single image blob for single multer upload, append more images with the same feild name for array upload
  // do not forget to provide the file name while appending the form data, otherwise it will be uploaded as blob file which further needed a conversion 

  //call your node server api here and send the imgData
  var uri = encodeURI("node server api to upload with multer");
  $.ajax({
    url: uri,
    data: imgData,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    error: function(err) {
      console.log('AJAX ERROR: ' + err);
      //handle the error response if any
    },
    success: function(result) {
      //handle the success response here if any
    }
  });
}

Node Server
Multer

var express = require('express');
var multer  = require('multer');
var app = express();

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, '/tmp/my-uploads')
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now())
  }
});

var upload = multer({ storage: storage }).single('image'); // just make sure field name should be same as client form data field name

// To upload multiple image 
//var upload = multer({ storage: storage }).array('images', maxCount);
// req.files is array of `images` files
// maxCount files could be uploaded 

app.post('/uploads', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})

Conclusion
In this article I have tried to cover it all which is essential to complete the task and you learn how to download/upload an image/file with node server which require the javascript knowledge nothing else.

Top comments (0)