0

Cheers mates!
I´m trying to make a file upload in my MEAN Application with GridFS. I´m using this tutorial http://www.codetutorial.io/file-upload-gridfs-mean-stack-meanjs/ .

After implementing it and checking it ten times, I still get this error: TypeError: Cannot read property "filefield" of undefined in the upload.server.controller.js. But it seems to me that the filefield is passed correctly to the route and to the controller.

Here´s my html form:

<form action="/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="filefield">
<button type="submit">Hochladen</button>
</form>

The route:

var upload = require ('./controllers/upload.server.controller');
app.route('/upload/:filename')
    .get(upload.read);
app.route('/upload/')
    .post(upload.create);

And the create-part of the controller:

'use strict';

var mongoose = require('mongoose'),
    _ = require ('lodash');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs = new Grid(mongoose.connection.db);

exports.create = function(req, res) {

    var part = req.files.filefield;

    var writeStream = gfs.createWriteStream({
        filename: part.name,
        mode: 'w',
        content_type:part.mimetype
    });

    writeStream.on('close', function() {
        return res.status(200).send({
            message: 'Success'
        });
    });

    writeStream.write(part.data);

    writeStream.end();
};

Anybody got an idea how to fix this error?
Best regards from Germany,
David

David Nnamremmiz
  • 191
  • 1
  • 2
  • 13

2 Answers2

0

Probably you forgot to include a body parser in your index.js file:

busboyBodyParser = require('busboy-body-parser'),
app.use(busboyBodyParser());

Without it there is no files in req object.

vanadium23
  • 3,516
  • 15
  • 27
0

You maybe have placed

  app.use(busboyBodyParser()); 

at the end. Try to place it upper. It will work.