6

I know this question has been asked plenty of times before, and I've tried implementing those solutions, but they don't really work for me.

I have been tearing my hair out trying to figure out how to upload a file and read the file size through Node. I initially tried using the formidable npm, which seems to no longer be maintained as I can't find documentation on it. I had no way of dealing with the errors so I tried using multer. However, I repeatedly get an undefined log when I try to log req.file.

I have the server.js code below

var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');

var app = express();

var PORT = 8080;

app.use(express.static(__dirname+'/views'));

app.set('views', './views');

app.set('view engine', 'jade');

app.get('/', function(req, res){
   res.render('index.jade'); 
});

app.post('/upload', upload.single('Upload'),function(req, res){
    console.log(req.file);
});

app.listen(PORT, function(){
    console.log('Express listening on port: '+PORT);
});

My javascript code with the AJAX call is provided below

$('#upload-butt').on('change', function(){
      var file = $(this).get(0).files;
      console.log(typeof file);

      if(file.length > 0){
          var formData = new FormData();
          formData.append('Upload', file, file.name);
          $.ajax({
              url: '/upload', 
              type: 'POST',
              data:formData,
              processData:false,
              contentType:false,
              error: function(jXhr, status){
                  console.log('error: '+status);  
              },
              success: function(data){
                  console.log('upload successful: '+data);
              }
          })
      }
   });

My index.jade code is given below

html
head
    link(rel='stylesheet', href='style.css', type='text/css')
    title Upload file for shortening
body
    h1 Welcome to file metadata service
    div(id='upload-button')
        form(enctype='multipart/form-data', method='post', action='/upload')
            input(name='Upload', type='file', id='upload-butt')
    div(id="submit-button")
        form(action = '/submit')
            button(type="submit", value='Submit', id='submit-butt') Submit

    script(src="https://code.jquery.com/jquery-2.2.0.min.js")
    script(src="upload.js")

I am ready to tear my hair out, so I will be very grateful to anyone who can help me here! Thanks!

2 Answers 2

0

You have not applied middle correctly.

You can use something like this:

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

var app = express()
app.use(multer({ dest: './uploads/'}))
You can access the fields and files in the request object:

console.log(req.body)
console.log(req.files)

So similarly in ur code you have to apply

var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');

var app = express();

var PORT = 8080;

app.use(upload);

app.use(express.static(__dirname+'/views'));

app.set('views', './views');

app.set('view engine', 'jade');

app.get('/', function(req, res){
   res.render('index.jade'); 
});

app.post('/upload', upload.single('Upload'),function(req, res){
    console.log(req.file);
});

app.listen(PORT, function(){
    console.log('Express listening on port: '+PORT);
});
Sign up to request clarification or add additional context in comments.

1 Comment

This returns the following error TypeError: app.use() requires middleware functions Also, it doesn't mention anywhere in the multer docs that we need to use app.use() to invoke middleware. Middleware is invoked as part of the get request method. npmjs.com/package/multer
0

You're submitting a different <form> than the one with the image, the correct way is to place all content in a single <form>. This way you're submitting the form which includes the file.

html
head
    link(rel='stylesheet', href='style.css', type='text/css')
    title Upload file for shortening
body
    h1 Welcome to file metadata service
    div(id='upload-button')
        form(enctype='multipart/form-data', method='post', action='/upload')
            input(name='Upload', type='file', id='upload-butt')
            button(type="submit", value='Submit', id='submit-butt') Submit

    script(src="https://code.jquery.com/jquery-2.2.0.min.js")
    script(src="upload.js")

This should work, for the jade part.

(docs about multer)

5 Comments

Tried this, and it didn't really make a difference because I'm not using the Submit button at all. I meant to remove it, but I just forgot about that. req.file still console logs undefined.
So in that case, why are you making an ajax call with jQuery, pressing the form submit button should trigger a valid post request on the spot, right?
Do you get the succes notification from the jQuery?
I wasn't completely sure how to make the submit button interact with the POST request. I was under the impression that you had to make an AJAX request anyway. Either ways, I got rid of the submit button.
Yeah, I get the success notification from jQuery. But the data variable in the callback is just a string that reads success. I thought the data variable was supposed to be an object or buffer containing the file uploaded.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.