Skip to main content

Create a File Upload Service using Node.js / Express / Multer

Problem:   
I needed to create a form that essentially uploads a file to a server, then posts the rest of the form data to a second server with the new file name. In other words, post the image to an “Image” server, then posts the form data (with the file URL) to a “Form Data” server.

Solution: 
Create an Express server that uses the “Multer” library to accomplish this.

The Code:
Create the express server and have it listen on a specific port

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

app.listen( 3313, function(){
   
console.log('listening on port 3313');
});

Install Multer.  Read here:

Include Multer to your express app.  We’ll be tweaking the storage properties so you can name the file whatever you like. At the end, you should have an “upload” object you’ll be using in the next step. be sure to change the file destination of your choice.

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

var multer = require('multer');

var storageProperties = multer.diskStorage({

    destination: function (req, file, callback) {

        callback(null, 'files/') //file destination

    },

    filename: function (req, file, callback) {

        callback(null, Date.now() + '_' + file.originalname )

    }

});

var upload = multer({ storage: storageProperties });

app.listen( 3313, function(){

    console.log('listening on port 3313');

});

Create you’re express route that fires then upload.single() method. “Thumbnail” is the name of the HTML input object.  We’ll show the form HTML after the service is created.

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

var storageProperties = multer.diskStorage({

    destination: function (req, file, callback) {
        callback(null, 'files/')
    },

    filename: function (req, file, callback) {
        callback(null, Date.now() + '_' + file.originalname )
    }
});

var upload = multer({ storage: storageProperties });

app.post('/upload',upload.single('thumbnail'), function (req, res) {
    res.json({file: req.file});
});

app.listen( 3313, function(){
    console.log('listening on port 3313');
});

That’s pretty much it for the service. Make sure to start your Node service you just created.  You should get a console message “Listening on port 3313” when it’s started successfully.  When that’s done, Let’s create a simple form to test it. Notice the settings below. your action should point to your node server, and name the file input element “thumbnail”.

<form method="post" enctype="multipart/form-data" action="http://localhost:3313/upload">

    <input type="file" name="thumbnail">

    <input type="submit">

</form>

Submit the form, and you should get the json back, like this:

{  
   
"file":{  
      
"fieldname":"thumbnail",
      
"originalname":"No Stranger.docx",
      
"encoding":"7bit",
      
"mimetype":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      
"destination":"files/",
      
"filename":"1461607365010_No Stranger.docx",
      
"path":"files\\1461607365010_No Stranger.docx",
      
"size":17566
   
}
}

 This means you successfully submitted the form. Confirm that your folder contains the uploaded file.

Conclusion:
Node.js saves A LOT of dev time using awesome libraries like express and Multer.

References:


Comments

  1. Thank you for sharing the article. The data that you provided in the blog is informative and effective. Best Nodejs Training Institute

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. For many web applications that let users share papers, photos, and other types of material, file uploads are a necessary functionality. Multer is a well-liked middleware used for Handling file uploads in Node.js using Multer middleware.in the Node.js environment to effectively handle file uploads. We’ll look at how to use Multer to create file uploads in Node.js in this in-depth tutorial, which covers everything like Multer typescript, Multer javascript from set up to save the configuration, and how to use Multer in node js, Multer GitHub and Step-by-step guide for file uploads with Multer in Node.js and how to implement file uploads in node.js using Multer?

    ReplyDelete

Post a Comment

Popular posts from this blog

Resolved Sitecore "If you publish now, the selected version will not be visible on the web site" warning

The Problem:   Unable to publish any Sitecore item within a particular site, even out of the workflow. Rather, a warning reads " If you publish now, the selected version will not be visible on the web site " What I've Discovered: I couldn't publish any item in the site, not just one or two I viewed all parent items of the items in question The main home page displayed a different warning " This item will never be published because it's publishable option is disabled " Another sitecore developer reminded me of the standard fields option View --> check standard fields to show all standard page fields Found out that somebody checked Never Publish within the publishing section The Fix: After I unchecked the checkbox and saved the change, I was able to publish again.  :) Conclusion: Looks like another Sitecore user thought the children items would not be affected by this change.  Lesson  learned.

[Resolved] Sitecore ParseException: End of string expected at position...

Problem:  I have a line of code that uses Sitecore Fast Query to pull all items + children starting with a site item, like so: Item [] allItems = db.SelectItems( "fast:" + sitecorePath + "//*" ); Unfortunately, I would get a Sitecore parsing error at runtime: ParseException: End of string expected at position... Turns out Sitecore doesn't like hyphens ('-') in any sitecore path when using fast query, which I have a few distributor sites in a folder which contained hyphens. Solution: I create a simple method that resolves a sitecore path to be Sitecore fast query friendly:             string sitecorePath = "" ;             if (siteItem.Paths.FullPath.Contains( "-" ))             {                 String [...