DEV Community

abhigsri
abhigsri

Posted on

1 1

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.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay