2014-04-01 74 views
2

我正在用angularJS編寫這個網頁,我希望人們編輯和存儲文本和圖像。我已經創建了一個文件上傳功能,讓你從用戶電腦上傳文件。問題是將這個文件存儲到mongoDB中。我已經閱讀了很多關於gridFS的例子,但沒有一個與我想要做的很相似。 這裏是我的代碼:使用gridFS在mongoDB中存儲文件(圖像)

網絡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; 
} 

在當我運行代碼,我沒有收到任何錯誤消息的那一刻,但db.files或db.chunks中存儲的圖像也不是。任何幫助表示讚賞。

+0

我想知道同樣的事情。回答此問題的人將獲得+1 – user2925894

回答

2

GridFS的流通常存儲它的數據在db.fs.files/db.fs.chunks如果不是由用戶設定。

要改變這一點,你必須補充:

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

到GridFS的流選項。

從NPM文檔:

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: { 
     ... 
    } 
} 

更多見https://www.npmjs.org/package/gridfs-stream

相關問題