【问题标题】:Uploading picture with Angular, Express, Mongoose使用 Angular、Express、Mongoose 上传图片
【发布时间】:2017-02-10 10:32:09
【问题描述】:

我正在尝试使用 Mongoose、Express 和 Angular 上传和存储图片。我在这里选择了下一个解决方案:

.directive('fileModel', ['$parse', function ($parse) {
        return {
           restrict: 'A',
           link: function(scope, element, attrs) {
              element.bind('change', function(){
              $parse(attrs.fileModel).assign(scope,element[0].files)
                 scope.$apply();
              });
           }
        };
     }])

以及控制器中的下一个功能:

$scope.uploadFile=function(){
   var fd = new FormData();
   angular.forEach($scope.files,function(file){
               fd.append('file',file);
           });

           $http.post('http://' + host + ':3000/users/' + $scope.selectedTask._id,fd,
              {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
              }).success(function(d){
                  console.log('yes');
              })
            }

还有html:

 <input type = "file" file-model="files" multiple/>
 <button ng-click = "uploadFile()">upload me</button>
 <li ng-repeat="file in files">{{file.name}}</li>

但由于某种原因,我在端点中得到的只是一个空请求对象。我正在使用 express.js 中的以下代码检查它:

user.route('/users/:id')
.post(function (req, res, next) {
    console.log(req.body);
})

我认为问题在于我不知道如何存储大于 16MB 的内容。

【问题讨论】:

  • 你为什么不使用 multer 一个节点包来帮助你存储任何类型的文件。如果你愿意,我可以告诉你如何使用它。
  • @sacDahal 这是我第一次听说,我是 node 新手。如果你告诉我如何上传图片,我会很高兴。但我想将它存储在 mongodb 中,因为我在那里有一个用户群,我想将图片与其他用户的数据一起存储。

标签: angularjs node.js express mongoose


【解决方案1】:

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

input(type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)")
button(ng-click='savePhoto()') Save 

在你的角度控制器中

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

      });

在您的架构中,将图像存储在 Buffer 类型中

img: { data: Buffer}

【讨论】:

  • 感谢您的回答。我正在努力使其立即工作,但是我遇到了一些困难。由于我没有玉文件,我只是添加了这个: 到我的视图。但是,我收到错误消息: Uncaught TypeError: angular.element(...).scope(...).selectFile is not a function
  • 你可以使用 html ,你不需要jade 我懒得打字所以我复制了现有的jade文件。它只是
  • 对不起,我有点垃圾。我现在收到此错误:(index):48 Uncaught SyntaxError: missing ) after argument list 不知道它来自哪里
  • fd.append("file", $scope.files[0]); )) ;// 删除 )) 我猜在角度控制器中
  • 尝试 console.log 看看它到底在哪里崩溃。
猜你喜欢
  • 2011-07-06
  • 2018-03-19
  • 2021-07-05
  • 2016-06-14
  • 2018-09-22
  • 2018-01-14
  • 1970-01-01
  • 2018-11-23
  • 2020-11-06
相关资源
最近更新 更多