【问题标题】:How do I upload images using MongoDB + Node.js (Express.js)?如何使用 MongoDB + Node.js (Express.js) 上传图片?
【发布时间】:2016-12-09 19:40:18
【问题描述】:

如果相关的话,我也使用 Mongoose。我正在尝试允许用户上传个人资料图片。一定有简单的方法吧?

【问题讨论】:

标签: node.js image mongodb express mongoose


【解决方案1】:

我认为你应该试试 multer。

简单来自 multer 网站:

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

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

它应该将文件上传到您的上传文件夹(在根目录下),并以 JSON 格式返回文件。

【讨论】:

    【解决方案2】:

    在此示例中,您将看到如何将您发送的文件存储到您的服务器目录中,然后从那里提取并保存它们。您也可以直接保存它们。首先,您使用 Angular 获取文件,您可以使用任何东西,如果您愿意,可以在此处查看更多详细信息。这是我的小例子,代码是jade。

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

    因此,这里的图像将存储在您服务器的此路径 (public/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);
    
          });
    

    【讨论】:

    • 图片存入db后如何从/public/assets/img/profile/中删除?
    • @TeodorKolev 需要 fs 模块并使用 fs.unlink 传递路径作为参数。
    猜你喜欢
    • 2016-12-16
    • 2018-12-17
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2016-03-17
    • 2019-12-31
    • 2011-07-06
    相关资源
    最近更新 更多