Question

I'm writing this web-page in angularJS where I want people to edit and store text and images. I've created a file uploading function that let's you upload files from the users computer. The problem is getting this file stored into mongoDB. I've read alot of examples on gridFS but none of them quite matched what I'm trying to do. Here's my code:

web-server.js:

app.post('/uploadFile', function(req,res){
console.log("Retrieved:");
console.log(req.files);

var Grid = require('gridfs-stream');
var gfs = Grid(DB, mongoose.mongo);
// streaming to gridfs
var writestream = gfs.createWriteStream(req.files.file);    
fs.createReadStream(req.files.file.path).pipe(writestream);

services.js:

function uploadFilesToServer(file){ 
    var fd = new FormData();
    fd.append("file", file);
    var deferred = $q.defer();
    console.log("trying to save:");
    console.log(file);
    $http({
        method:"POST",
        url: "uploadFile",
        data: fd,
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success(function(data){
        var returnValue = [true, file, data];
        deferred.resolve(returnValue);
    }).error(function(data){
        var returnValue = [false, file, data];
        deferred.resolve(returnValue);
    });
    return deferred.promise;
}

At the moment I'm not getting any error messages when I run the code, but neither is the images stored in the db.files or db.chunks. Any help is appreciated.

Was it helpful?

Solution

GridFS-stream usually stores it's data in db.fs.files/db.fs.chunks if not set by the user.

To change this, you'll have to add:

{
   ....
   root: 'my_collection'
   ....
}

to gridfs-stream options.

From NPM docs.:

createWriteStream

To stream data to GridFS we call createWriteStream passing any options.

var writestream = gfs.createWriteStream([options]);
fs.createReadStream('/some/path').pipe(writestream);
Options may contain zero or more of the following options...

{
    _id: '50e03d29edfdc00d34000001', // a MongoDb ObjectId
    filename: 'my_file.txt', // a filename
    mode: 'w', // default value: w+, possible options: w, w+ or r, 
    see [GridStore]    
    (http://mongodb.github.com/node-mongodb-native/api-generated/gridstore.html)

    //any other options from the GridStore may be passed too, e.g.:

    chunkSize: 1024, 
    content_type: 'plain/text', 
    // For content_type to work properly, set "mode"-option to "w" too!
    root: 'my_collection',
    metadata: {
        ...
    }
} 

See https://www.npmjs.org/package/gridfs-stream for more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top