0

I am trying to upload an image to my MongoDB. I'm using Mongoose, gridfs-stream and some other packages I was told to install (I'm relatively new to the whole MEAN ecosystem)

The request seems to go through fine, and the collections used for fs-stream do get auto added to my db, but the request always seems to time out with no error being returned and nothing being logged by nodemon.

Here is my code:

const router = require('express').Router();
const database = require('../config/database');
var mongoose = require('mongoose');

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


router.get('/', function(req, res) {
    res.send("Greetings!");
})

router.post('/img', 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.end();
    })
});

I have tried running the mongodb locally, and on mlab, I have also tried images of varying sizes, most of which were less than 10MB and some less than 1MB. I'm at a loss of where to go from here as my research into the matter has also offered no answers.

geolaw
  • 412
  • 1
  • 12
  • 26
  • You don't actually put anything into the stream. See the [documentation](https://github.com/aheckmann/gridfs-stream#createwritestream) which actually shows picking up a file and using `pipe()` to direct to the stream input. Things like `filename` as an argument are just "metadata", so it does not actually "open the file". That's up to you to code. – Neil Lunn Apr 25 '18 at 11:02
  • Thanks for the comment, I am trying to pipe the writestream as you said to `readStream` but I am not sure what to pass it as '/some/path' is quite ambiguous – geolaw Apr 25 '18 at 11:28
  • What are you actually using for the file upload handling? Different middleware has different options, but most have a choice between "in memory" and "storing a temporary file". You want the latter configuration, and there should be a file descriptor or at least the path to the temporary file within the `req.files` object. This will allow you to open the file into to pipe to the `writeStream` – Neil Lunn Apr 25 '18 at 11:31
  • I believe it's using just the express router. The only descriptor I can find in the req.files object is inside the fileField object containing the image, there is no path, only the file name of the image – geolaw Apr 25 '18 at 12:28
  • Correction: I am using BusBoyBodyParser for multipart/form-data requests I am currently reading up on how to extract the needed stuff from it – geolaw Apr 25 '18 at 12:38

0 Answers0