2014-04-01 4 views
2

저는 사람들이 텍스트와 이미지를 편집하고 저장하기를 원하는 angularJS에이 웹 페이지를 작성하고 있습니다. 사용자 컴퓨터에서 파일을 업로드 할 수있는 파일 업로드 기능을 만들었습니다. 문제는이 파일을 mongoDB에 저장하는 것입니다. 나는 gridFS에서 예제를 많이 읽었지만 그 중 누구도 내가하려는 것을 일치하지 않았습니다. 내가 코드를 실행할 때이 오류 메시지를받지 못했습니다 순간gridFS를 사용하여 mongoDB에 파일 (이미지) 저장하기

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

:

웹 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 다음은 내 코드입니다 db.files 또는 db.chunks에 저장된 이미지는 없습니다. 어떤 도움을 주셔서 감사합니다.

+0

나는 똑같은 것을 궁금해하고있었습니다. 응답하는 사람은 +1을 받게됩니다. – user2925894

답변

2

GridFS-stream은 일반적으로 사용자가 설정하지 않은 경우 데이터를 db.fs.files/db.fs.chunks에 저장합니다.

이를 변경하려면, 당신은 추가해야합니다 : gridfs 스트림 옵션

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

. 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를 참조하십시오.