Instructions for uploading a file in MongoDB without using GridFS and specifically with BSON

I am facing an issue with storing files, images, and documents in MongoDB. Currently, it only accepts null values. Despite being able to store the file in a folder successfully, I am encountering difficulties when trying to do the same in Mongo.

Below is the content of the .ejs file:

<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>

The corresponding JavaScript file looks like this::

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


}]);

The controller file in API is structured as follows::

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


    });
 }  };

The model in API is as shown below::

module.exports = {


  schema: true,
  attributes: {




     up: {
    type: 'jpg',
     columnName: 'up' 
    },

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



  }
};

This particular code snippet from my Sails controller includes GridFS coding. Please review it thoroughly.

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


}

}

}

Answer №1

If you are interested in storing files in a mongoDB database, consider exploring GridFS

GridFS is a method for storing and retrieving files that go beyond the maximum size limit of BSON documents, which is 16 MB.

Instead of storing an entire file in one document, GridFS breaks the file into chunks 1, and saves each chunk as a separate document. By default, GridFS uses a chunk size of 255 kB; this means that files are divided into chunks of 255 kB except for the last chunk, which is only as large as necessary. Files smaller than the chunk size will have just one final chunk, utilizing space efficiently along with additional metadata.

GridFS utilizes two collections to store files: one collection holds the file chunks, while the other stores file metadata. The GridFS Collections section provides further information on each collection.

When requesting a file from GridFS, the driver will piece together the chunks when necessary. It allows for range queries on stored files and enables access to specific sections of a file, like jumping to the middle of a video or audio file.

GridFS is not only beneficial for handling files larger than 16 MB but also for managing any files where selective access without loading the entire file into memory is desired.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML5 Drag and Drop: How to Stop Drag and Drop Actions from Occurring Between a Browser and Browser Windows

Is it possible to restrict HTML5 Drag & Drop functionality between different browsers or windows? I am currently working on an Angular2 app that utilizes native HTML5 Drag and Drop feature. Is there a way to prevent users from dragging items out of th ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

code for handling window.location.href error

Continuing from the previous question, I am facing an issue with redirecting a form to an action while using Ajax. Despite my attempts to add a redirect in the Ajax function, I keep encountering errors and getting the wrong URL. The desired redirection is ...

Unable to effectively select all checkboxes using jQuery

I can't seem to figure out why my code isn't working and I need help. My goal is to select all checkboxes when clicking on "Todas". I created a JSFiddle demo where the code works perfectly. However, when I implement it in my project, it fails w ...

JS limits browsers to downloading only 10 images simultaneously

Is there a way to increase the number of simultaneous downloads beyond the current limit of 10 in the code below? transferFiles(){ this.checkMark = true let i = 0 this.finalImages.forEach((image) =>{ i++ saveAs(image, 'imag ...

Generate and display a word document using JavaScript instead of prompting for a download

Is it possible to have a link that, when clicked, opens a print window for a .docx or PDF file instead of downloading or displaying the file directly? I attempted to achieve this with the following code snippet but encountered an error: var e = docume ...

The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products. Below is the function responsible for calculating ...

How can you show binary information within an <img /> element on a web browser?

Here is an example of data stored in MongoDB: avatar:Binary('iVBORw0KGgoAAAANSUhEUgAAAPoEAmpwR42ny9h3db17Xuq//g...', 0) This is how the data appears in a response using Postman: { "avatar": { "type": "Buffer&quo ...

Tips for resolving the 'route.search' bug in Express.js

I recently started working on a basic Express app (with Node) and I am in the initial setup phase. However, I have encountered an error that is proving to be quite challenging to resolve. Despite my attempts to search for solutions online and browse throu ...

How can I make a bootstrap offcanvas disappear in Vue 3 after clicking a router-link?

Hey there! I'm looking to close the bootstrap-5 Offcanvas when I click on a link inside it. Here's the code for the Offcanvas: //Button activate Offcanvas <button class="navbar-toggler" type="button" data-bs-toggle=&quo ...

Are you looking to conduct comprehensive UI tests for a team-based web application?

Our web application is designed for collaborative use, so actions by one user in their browser affect another user's experience. A prime example of this functionality can be seen in our chat room feature. The technology stack we are currently using i ...

When deploying, Heroku fails to provide specific PORT information

Here is my index.js file: const PORT = process.env.PORT || 8453; app.listen(PORT, () => console.log("Server is now listening on port: " + PORT)); However, when checking the deploy logs, I see: Running build (yarn) yarn run v1.22.4 $ node src/index.j ...

Ways to extract transparency data of each pixel from a PNG uploaded by the user via the front-end

Currently, I am in need of extracting the transparency value for each individual pixel from a PNG image that is submitted by the user, directly within the front-end environment. At the moment, I have implemented a method where I prevent the form from bein ...

Is there a way to display current data in angularJS based on the current time?

My database contains timestamps like 2016-12-30 00:30:10 which I retrieve using the $http module in Angular. Below is a snippet of my Angular code: angular .module('sampleApp') .controller('ReportCtrl', ReportCtrl) ...

I included an onPress prop where I am triggering a handleEvent function, but unfortunately no output is being displayed within the method

I'm currently working on implementing a textbox similar to Google Flights. As a result, I've developed a React autocomplete prototype. However, I've encountered an issue with it. In the Google Flights search box, all results are displayed wh ...

Slanted lower edge - entire width

Can anyone provide guidance on how to design a div that is 100% width and 300px wide, with a slightly angled bottom border that spans the entire width of the box? https://i.sstatic.net/QSvoQ.png I am open to using either CSS or JavaScript for this task, ...

Error in MongoDB: 'MongoServerSelectionError'

After smoothly running my code for the past two weeks and successfully connecting to mongo with millions of items stored in my database, suddenly today I encountered a problem. The error message that appeared stated: { MongoServerSelectionError: connect EC ...

Unable to visualize object in three.js

Looking to generate cubes in a random location on the page using a for loop, but currently experiencing issues where the cubes are not appearing as expected. **Note: When I check the cube with console log, this is the output: ** -cube.js:24 Mesh {uuid ...

Unable to successfully test POST request with node, express, mocha, and MongoDB

Having trouble with testing POST requests using node, express, mocha, and MongoDB. Oddly enough, the post request works fine in insomnia but I keep getting an error message that says Uncaught AssertionError: expected 404 to equal 200. app.spec.js process. ...