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