Tuesday 9 May 2017

upload file with gridfs-stream & mongoose to server (heroku, mlab) ENOENT: no such file or directory

I'm trying to upload file to mongodb with mongoose and gridfs-stream using this code. This code works fine when I'm trying it locally, with path as parameter

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Types.ObjectId;
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs;

mongoose.connection.once('open', function () {
    gfs = Grid(mongoose.connection.db);
});

function putFile(path, name, callback) {
    var writestream = gfs.createWriteStream({
        filename: name
    });
    fs.createReadStream(path).pipe(writestream);
    writestream.on('close', function (file) {
        callback(null, file);
    });
}

exports.addFile = function (req, res) {
    var arr = req.body.path.split("\\");
    var name = arr[arr.length - 1];
    if (req.body.name) {
        var name = req.body.name;
    }
    putFile(req.body.path, name, function (err, file) {
        if (err) {
            res.json(err);
        } else {
            console.log(file);
            res.json({
                success: true,
                message: "successfully added " + file.filename + " to database"
            });
        }
    });
}

This is my query

URL: http://localhost:8080/files
Body: { "name": "Event.txt", "path": "D:\\Works\\Event.txt" }

And this is my response:

Response: { success: true, message: "successfully added Event.txt to database' }

But when I try that on the server, I got this response

Response: {
  "code": "InternalError",
  "message": "ENOENT: no such file or directory, open 'D:\\Works\\Event.txt'"
}

I'm using heroku with mlab addons

I think this happens because the file is not exists on the server and can't be found, that's why it works when I try it locally.

Are there any different approach to upload the file without the local path used at fs.createReadStream(path).pipe(writestream)? Like using with multipart for / base64 string



via fadeltd

No comments:

Post a Comment