3
votes

I created a simple file uploading application with loopbackjs. In the application's client side I used simple HTML and Javascript code, calling a loopback api with an AJAX call:

$('#upload-input').on('change', function () {

    var files = $(this).get(0).files;

    if (files.length > 0) {
        // One or more files selected, process the file upload
        var form = new FormData();

        for (var index = 0; index < files.length; index++) {

            var file = files[index];
            form.append('Uploded Files', file, file.name);
        }

        $.ajax({
            url: 'api/fileupload/upload',
            type: 'POST',
            data: form,
            processData: false,
            contentType: false,
            success: function (data) {
                console.log('upload successful!');
            }
        });
    }

});

We are not getting files on the server side. On the server side we created a Loopback API, but how can we upload files with this API?

This is my loopback API code:

FileUpload.remoteMethod

(
        'upload', {
            http: {
                verb: 'post',
            },
            accepts:
            [
                { arg: 'ctx', type: 'object', http: { source: 'context' } },
                { arg: 'options', type: 'object', http: { source: 'query' } }

            ],
            returns: {
                arg: 'data',
                type: 'string',
                root: true
            }
        }
    );

    FileUpload.upload = function (context, options, callback) {
        //context.req.params = 'common';

    };
4
did u check loopback-storage-component - loopback.io/doc/en/lb3/Storage-component.html - Aks1357
Yes , But how can we used it !! please clarify - Rakesh
Thanks , we need to store files on Server side not in Container . - Rakesh
check the link, it has steps to implement it, also link to example - github.com/strongloop/loopback-example-storage - Aks1357
Conatiners are nothing but folders on server side, will give another option as answer as it won't fit in comment box - Aks1357

4 Answers

8
votes

Install multer : https://github.com/expressjs/multer

npm install --save multer

In MyModel.js

var multer = require('multer');
var fs = require('fs');

module.exports = function (MyModel) {
    var uploadedFileName = '';
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            // checking and creating uploads folder where files will be uploaded
            var dirPath = 'client/uploads/'
            if (!fs.existsSync(dirPath)) {
                var dir = fs.mkdirSync(dirPath);
            }
            cb(null, dirPath + '/');
        },
        filename: function (req, file, cb) {
            // file will be accessible in `file` variable
            var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
            var fileName = Date.now() + ext;
            uploadedFileName = fileName;
            cb(null, fileName);
        }
    });


    MyModel.upload = function (req, res, cb) {
        var upload = multer({
            storage: storage
        }).array('file', 12);
        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                res.json(err);
            } else {
                res.json(uploadedFileName);
            }
        });        
    };

    MyModel.remoteMethod('upload',   {
        accepts: [{
            arg: 'req',
            type: 'object',
            http: {
                source: 'req'
            }
        }, {
            arg: 'res',
            type: 'object',
            http: {
                source: 'res'
            }
        }],
        returns: {
             arg: 'result',
             type: 'string'
        }
    });
};

Frontend - I use AngularJS, so for that follow -https://github.com/nervgh/angular-file-upload

there are also other such directives to use

P.S. - As per your comment - Actually Our Problem is that , we need to upload a File from Client Side and Store this File in Database , But Before save in DB , we need to get files on Server side , if we get Files on Server side via Post API than we can easily store file in DB

Can't provide you exact solution, but using above method files will be uploaded in your /client/uploads folder, once uploaded then you have control on what to do with file and once everything is done, eventually delete it(optional)

1
votes

Please check this code:

module.exports = function (FileUpload) {
var multer = require('multer');

    FileUpload.remoteMethod(
        'upload', {
            http: {
                verb: 'post',
            },
            accepts:
            [{
                arg: 'req',
                type: 'object',
                http: {
                    source: 'req'
                }
            }, {
                arg: 'res',
                type: 'object',
                http: {
                    source: 'res'
                }
            }],
            returns: {
                arg: 'data',
                type: 'string',
                root: true
            }
        }
    );

    var uploadedFileName = '';

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            // checking and creating uploads folder where files will be uploaded
            var dirPath = 'client/uploads/'
            if (!fs.existsSync(dirPath)) {
                var dir = fs.mkdirSync(dirPath);
            }
            cb(null, dirPath + '/');
        },
        filename: function (req, file, cb) {
            // file will be accessible in `file` variable
            console.log("----------Second Rakesh---");
            console.log(file);
            var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
            var fileName = Date.now() + ext;
            uploadedFileName = fileName;
            cb(null, fileName);
        }
    });

    FileUpload.upload = function (req, res, callback) {

        var upload = multer({
            storage: storage
        }).array('file', 12);

        upload(req, res, function (err) {
            if (err) {
                // An error occurred when uploading
                res.json(err);
            }
            console.log("-------------Rakesh"); // Its Printing Rakesh

            res.json(uploadedFileName);
        });
    };
};
0
votes

You can upload files/Images using loopback's default storage component. Go to the doc link and follow the instruction and specially look how the example project implemented the file uploading.

You will have to create a datasource and a container model for this purpose.

Create Datasource:

$ lb datasource
[?] Enter the data-source name: myfilesystem
[?] Select the connector for myfilesystem: other
[?] Enter the connector name: loopback-component-storage
[?] Install storage (Y/n)

create the container model:

  • Model name: Container
  • Data source: myfilesystem
  • Base class: Model
  • Expose Reviewer via the REST API? Yes
  • Custom plural form (used to build REST URL): Yes
0
votes

This worked for me using LoopbackJs

Loopback framework is based on ExpressJs by the way

You can consider this answer as and adapted version of https://github.com/blueimp/jQuery-File-Upload/ for LoopbackJs

Install plugin dependecy:

npm install jquery-file-upload-middleware

Add this snippet to your /server/server.js :

 //Load Jquery File Upload handler
      var upload = require('jquery-file-upload-middleware'),
        bodyParser = require('body-parser');

        // configure upload middleware
        upload.configure({
            uploadDir: __dirname + '/public/uploads',
            uploadUrl: '/uploads',
            imageVersions: {
                thumbnail: {
                    width: 80,
                    height: 80
                }
            }
        });



        app.use('/upload', upload.fileHandler());
        app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

Modify middleware.js with the following snippet so your app can serve static HTML resources in /client folder (this file belongs LoopbackJs framework BTW):

...
    "files": {
  "loopback#static": {
    "params": "$!../client" 
  }
}
...

Download and place in /client/test file-upload webpage : File Upload Webpage

Run your node.app and point to http://localhost:3000/files/ You should be able to upload files and found the uploaded filename response in the Network tab:

enter image description here