Handling file upload via multipart form post in Loopback custom remote method Handling file upload via multipart form post in Loopback custom remote method express express

Handling file upload via multipart form post in Loopback custom remote method


Tell me if that help you. With upload and check information in loopback3.

/server/server.js

var loopback = require('loopback');var bodyParser = require('body-parser');var multer = require('multer');var boot = require('loopback-boot');var app = module.exports = loopback();app.use(bodyParser.json()); // for parsing application/jsonapp.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencodedapp.use(multer().any()); // for parsing multipart/form-dataapp.start = function() {

/server/midleware.json

  "parse": {    "body-parser#json": {},    "body-parser#urlencoded": {"params": { "extended": true }}  },

final model:

module.exports = function(Offer) {    Offer.add = function (ctx,options,cb) {    console.log(ctx.req.body);    console.log(ctx.req.files[0]);     if(!options) options = {};    ctx.req.params.container = 'x';Container.upload(ctx.req,ctx.result,{container: 'x'},function (err,fileObj) {fileObj.files[''] ...

and remote my is different then your

 Offer.remoteMethod(    'add',    {      description: 'Uploads a file',      accepts: [        { arg: 'ctx', type: 'object', http: { source:'context' } },        { arg: 'options', type: 'object', http:{ source: 'query'} }      ],      returns: {        type: 'object', root: true      },      http: {verb: 'post'}    }  );

I use postman to send data explorer do not allow for files.Something explorer do some error.

with this options:address: http://0.0.0.0:3000/api/Offers/add?access_token=c6qlcG19lhEYp6C6CztcPHYKpXj2uA3qARMJU7nxBL3trjveHbxNTo0BsvV3vleO

type: POST

authentication: no authentication

headers: empty (default content type is included)

body: form-data with data you want to send

How to configure storage connector to filter size and type of file loopback:

      "storage": {    "name": "storage",    "nameConflict": "makeUnique",    "connector": "loopback-component-storage",    "provider": "filesystem",    "root": "./server/storage",    "maxFileSize": "5242880",    "allowedContentTypes":["image/gif", "image/png", "image/tiff", "image/webp", "image/x-icon", "image/jpeg", "image/svg+xml", "image/x-icon"]  }

How to create relation for model and file in loopback?How to save file info in loopback?You need to have model in data base what save name of file.

        Container.upload(ctx.req,ctx.result,{container: 'x'},function (err,fileObj) {cFile  =  fileObj.files[''][0];    Image.create({                 name: cFile.name,                 type: cFile.type,                 originalFilename: cFile.originalFilename,                   offerId: 3,                 container: "x"},    function (err, obj) { ...