2016-12-09 219 views
1

我也使用貓鼬,如果這是相關的。我正在嘗試允許用戶上傳個人資料照片。必須有一個簡單的方法,不是嗎?如何使用MongoDB + Node.js(Express.js)上傳圖片?

+0

你可以試試[multer(https://github.com/expressjs/multer) – bugwheels94

+0

的可能的複製[如何使用快車來的NodeJS上傳圖片文件並顯示(http://stackoverflow.com/問題/ 36477145 /如何上傳圖像文件和顯示使用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),以檢查是否在此處獲取文件。 Multer在這裏做魔術。

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

因此,這裏圖像將存儲在您的服務器中的這個路徑(公共/ assets/img/profile)。現在你從這個服務器拿起文件並添加到你的數據庫。

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傳遞路徑作爲參數。 –

相關問題