2016-12-09 17 views
1

私はMongooseも使用します。ユーザーにプロフィール写真をアップロードさせようとしています。簡単な方法がなければなりません、そうではありませんか?MongoDB + Node.js(Express.js)を使用して画像をアップロードするにはどうすればよいですか?

+0

あなたは試すことができます[multer](https://github.com/expressjs/multer)の – bugwheels94

+0

可能な重複[特急nodejsを使用して、イメージファイルとディスプレイをアップロードする方法](http://stackoverflow.com/質問/ 36477145/how-to-upload-image-file-and-display-using-express-nodejs) – RaR

答えて

0

私はあなたがマルチターを試すべきだと思います。 multerサイトからシンプル

var multer = require('multer') 
var upload = multer({ dest: 'uploads/' }) 

app.post('/upload', uploads.any(), function(req,res){ 
    res.send(req.files); 
}); 

それはあなたのアップロードフォルダ内のファイルをアップロードする必要があります(ルートの下)、およびJSONでファイルを返します。

0

この例では、送信するファイルをサーバーディレクトリに保存し、そこからファイルを選択して保存する方法を示します。また、それらを直接保存することもできます。最初に角度を使用してファイルをピックアップし、詳細を確認できるようにしたい場合は何でも使用できます。ここで私の小さな例は、コードがヒスイです。

<input type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)"/> 
<button ng-click="savePhoto()">Save </button> 
あなたの角度制御装置においては

$scope.savePhoto = function() { 
var fd = new FormData(); 
    fd.append("file", $scope.files[0]); 
)) ; 
$http.post("/xxx/photos", fd, { 
     withCredentials: true, 
     headers: { 'Content-Type': undefined }, 
     transformRequest: angular.identity 
     }).success(function (data) { 
     $scope.image = data; // If you want to render the image after successfully uploading in your db 
     }); 
    }; 

あなたのバックエンドでNPMを使用してmulterをインストールします。そして、app.jsであなたが送信しているファイルを収集するミドルウェアを設定することができます。ここまでファイルを取得しているかどうかを確認するためにここでconsole.log(req)を実行してください。マルターはここで魔法をやる。

app.use(multer({ 
    dest: path.join(__dirname, 'public/assets/img/profile'), 
    rename: function (fieldname, filename, req, res) { 
     console.log(req)// you will see your image url etc. 
    if(req.session.user) return req.session.user.id; 
    } 
})); 

ここで、画像はサーバーのこのパス(public/assets/img/profile)に保存されます。これで、このサーバーからファイルを取得し、dbに追加します。

var path = require('path'); 
    var imgPath =path.join(__dirname, '../public/assets/img/profile/' + id + '.jpg'); // this is the path to your server where multer already has stored your image 
     console.log(imgPath); 
     var a ; 

     a = fs.readFileSync(imgPath); 
     YourSchema.findByIdAndUpdate(id, { 
      $set: 
      {'img.data' : a, 
       'img.contentType' : 'image/png' } 
      }, function(err, doc) { 
      if (err)console.log("oi"); 

      } 
    ); 

    //In case you want to send back the stored image from the db. 
     yourSchema.findById(id, function (err, doc) { 
     if (err)console.log(err); 

     var base64 = doc.img.data.toString('base64'); 
     res.send('data:'+doc.img.contentType+';base64,' + base64); 

     }); 
+0

/public/assets/img/profile /から画像を削除するにはどうすればいいですか? – TeodorKolev

+0

@TeodorKolevはfsモジュールを必要とし、fs.unlinkをパスとしてパラメータとして渡します。 –

関連する問題