SOuřaan Gřg
SOuřaan Gřg

Reputation: 399

node js normal file upload code shows error while executing

I am trying a simple node.js file upload code for test purpose by using express and multer modules.My code look for html like :-

<html>
 <head>
   <title>File Uploading Form</title>
 </head>
 <body>
   <h3>File Upload:</h3>
       Select a file to upload: <br />
        <form action="http://127.0.0.1:8081/file_upload" method="POST" 
          enctype="multipart/form-data">
          <input type="file" name="file" size="50" />
          <br />
          <input type="submit" value="Upload File" />
        </form>
 </body>

and my server.js code look like :-

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

var bodyParser = require('body-parser');
var multer  = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));

app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
});

app.post('/file_upload', function (req, res) {

console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);

var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
    fs.writeFile(file, data, function (err) {
     if( err ){
          console.log( err );
     }else{
           response = {
               message:'File uploaded successfully',
               filename:req.files.file.name
          };
      }
      console.log( response );
      res.end( JSON.stringify( response ) );
     });
   });
 });

var server = app.listen(8081, function () {

var host = server.address().address
var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

 });

Now while I run the server.js from command prompt like :- node server.js My server doesn't get started and it throws some error like image :-

My error picture

Upvotes: 0

Views: 712

Answers (1)

Abdullah Rasheed
Abdullah Rasheed

Reputation: 3752

SOuřaan Gřg,

Your line, var multer = require('multer'); is returning and object, not the middleware function. There are three middleware functions you can use.

Check out the docs.

In case you need to handle a text-only multipart form, you can use any of the multer methods (.single(), .array(), fields()).

  • .single(fieldname)
    Accept a single file with the name fieldname. The single file will be stored in req.file.

  • .array(fieldname[, maxCount])
    Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files.

  • .fields(fields)
    Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files.

You must change app.use(multer({ dest: '/tmp/'}));. You are passing an object.

Also according to the docs:

WARNING: Make sure that you always handle the files that a user uploads. Never add multer as a global middleware since a malicious user could upload files to a route that you didn't anticipate. Only use this function on routes where you are handling the uploaded files.

You should be assigning the middleware to route in where you are handling the upload. For your case you could do the following:

var upload = multer({ dest: '/tmp/' });

app.post('/file_upload', upload.single('file'), function (req, res, next) {
  // req.file is the `file` file 
  // req.body will hold the text fields, if there were any 
})

Upvotes: 1

Related Questions