如何在mongodb中上传文件(BSON不需要gridfs)



我正在尝试将文件、图像和文档存储在mongodb中,但它只需要null,我可以将文件存储在文件夹中,但无法对mongo执行同样的操作。

ejs文件如下:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js">
</script>
</head>
<div class="container">
    <div class="row" ng-controller="PatientEmrController">
        <h1>Upload a file</h1>
        <div class="col-sm-4">
            <form ng-submit="uploadFile()" class="form">
                <input type="text" placeholder="title" ng-model="titleText" class="form-control" required>
                <br><br>

<file-field ng-model="uploadThis" class="btn" ng-class="{'btn-success':uploadThis}" preview="uploadPreview" name="up" accept="image/png,image/jpg,image/jpeg">Select file</file-field>
                <br><br>
                <input type="submit">
            </form>
        </div>
        <div class="col-sm-4">
            <img ng-src="{{uploadPreview}}" ng-if="uploadPreview" class="img-responsive" >   
        </div>
    </div>
</div> </html>

对应的js文件为::

sample.controller('PatientEmrController',['$scope','$http',function($scope,$http){
    $scope.uploadFile=function(){
        if(!$scope.uploadThis){
            alert('Please select a file to upload.')
            return;
        }
        var fd = new FormData();
        //you can also send other fields
        //this will be available as req.body.title
        //NOTE: files must be added AFTER other form data
        fd.append('title', $scope.titleText);
        //nacho relates to what we called the file
        //in the api on sails
        fd.append('nacho', $scope.uploadThis);
        $http.post('/api/burrito', fd, {
            //transformRequest: angular.identity,
            //headers: {'Content-Type': undefined}
            up:$scope.uploadThis,
            title: $scope.titleText,
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            console.log('upload data',data);
            if(data.result){
                alert('file uploaded. See .tmp/uploads folder.');
            }

        })
        .error(function(err){
            alert('there was an error uploading the file.');
            console.log(err);
        });        
    }

}]);

api中的控制器文件如下::

 module.exports = {

torta:function(req,res){
    console.log('form body',req.body);

    req.file('nacho').upload(function(err,files){


            Filecontroller2.create({
                up: req.param('up'),
              title: req.param('title')
           })

            .exec(function createCB(err, created){
                     if (err)
                      {
                       return res.negotiate(err);
                      }
                       else
                      {
                        return res.ok();
                      }
              });





        if(err) return res.send(400,{result:false,error:err});

        if(!files) return res.send(400,{result:false,error:'Unable to upload file'});

        console.log('file data',err,files);
        console.log('uploaded file path',files[0].fd)

        res.send({result:true,files:files});

    });
 }  };

api中的模型是:

module.exports = {

  schema: true,
  attributes: {


     up: {
    type: 'jpg',
     columnName: 'up' 
    },
    title: {
      type: 'string',
     // required: true
     columnName: 'title' 
    }

  }
};

这是我用gridfs编码的帆控制器代码,请看一下。

uploadAvatar: function (req, res) {

  console.log('form body',req.body);
  var patientID=req.session.me;
  req.file('avatar').upload(function(err,files){
    // don't allow the total upload size to exceed ~10MB
    //maxBytes: 10000000
    adapter: require('skipper-gridfs'),
    //uri: 'mongodb://[username:password@]host1[:port1][/[database[.bucket]]'
     uri:'mongodb://kal:kal@localhost:27017/medoolDB.bucket',
    },function whenDone(err, uploadedFiles) {
    if (err) {
      return res.negotiate(err);
      return res.ok();
    }
    // If no files were uploaded, respond with an error.
    if (uploadedFiles.length === 0){
      return res.badRequest('No file was uploaded');
    }

    filecontroller2.findOne({patientID:patientID}, function foundFilecontroller(err, fcontroller) {
    console.log(req.method);
      if (err) return next(err);
      if (!fcontroller){
             filecontroller2.create({
                 up:req.param('up'),
      })
             .exec(function createCB(err, created){
                       if (err)
                          {
                           return res.negotiate(err);
                          }
                           else
                          {
                               return res.ok();
                          }
                  });
            }
            else
            {

    // Save the "fd" and the url where the avatar for a user can be accessed
    filecontroller2.update({ patientID:patientID}, {
      // Generate a unique URL where the avatar can be downloaded.
      avatarUrl: require('util').format('%s/user/avatar/%s', sails.getBaseUrl(), req.session.me),
      // Grab the first file and use it's `fd` (file descriptor)
      avatarFd: uploadedFiles[0].fd
    })
    .exec(function (err){
      if (err) return res.negotiate(err);
      return res.ok();
    });

    if(err) return res.send(400,{result:false,error:err});
    if(!files) return res.send(400,{result:false,error:'Unable to upload file'});
     console.log('file data',err,files);
     console.log('uploaded file path',files[0].fd)

            //send response
            //result:true -- file upload successful
            //files:files -- send uploaded file data to the front end
            res.send({result:true,files:files});

}
}
}

如果您想将文件存储到mongoDB中,请查看GridFS

GridFS是用于存储和检索超过BSON文档大小限制为16MB。

GridFS不是将文件存储在单个文档中,而是将文件分为多个部分或块1,并将每个块存储为单独的文件默认情况下,GridFS使用255 kB的块大小;即,GridFS将文件划分为255 kB的块最后一块。最后一个区块只有在必要时才大。类似地,不大于块大小的文件仅具有最终块,只使用所需的空间加上一些额外的元数据。

GridFS使用两个集合来存储文件。一个集合存储另一个存储文件元数据。GridFS部分集合详细描述了每个集合。

当您查询GridFS中的文件时,驱动程序将重新组装块。可以对存储的文件执行范围查询通过GridFS。您还可以从任意文件的部分,例如"跳过"到视频或音频的中间文件

GridFS不仅适用于存储超过16MB的文件,而且用于存储您想要访问的任何文件,而无需加载将整个文件放入内存

相关内容

最新更新