Monday, 17 April 2017

File Upload With NodeJS and Loopback API

I am new with NodeJS and loopback . I created a Simple file uploading Application with loopback. Application client side i used simple html and Java Script code -

i calling a loopback api with ajax call , this is Java Script complete code -

$('#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!');
        }
    });
}

});

I need to take any file as input from user and Save this file in a folder on Server Side .

But i am not getting files object on server side . On Server side i Created a Loopback api .

can any help us , how to upload files with loopback api .

This is my loopback api code -

 module.exports = function (FileUpload) { var multer = require('multer');ileUpload.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("----------its not printing 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);
});

}; };



via Rakesh

No comments:

Post a Comment