loopback - Upload files from another model
Asked Answered
P

1

0

I have two models:

container: handles file uploading and works fine in loopback explorer.

Crawler: have multiple properties. one of the properties is script that user can upload a script file to this model.

crawler.json:

{
  "name": "Crawler",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "script": {
      "type": "string"
    },
    "startCount": {
      "type": "number",
      "default": 0
    },
    "created_at": {
      "type": "date"
    },
    "updated_at": {
      "type": "date"
    }
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

crawler.js:

module.exports = function(Crawler) {
  Crawler.upload = function (id,req,res,cb) {
    var container = Crawler.app.models.container;
    container.getContainers(function(er,containers){
      console.log(containers);
      if (containers.some(function(e){return e.name == 'script';})) {
        container.upload(req,res,{container:"script"},cb);
      }else{
        container.createContainer({name: "script"}, function(er,c){
          container.upload(req,res,{container: "script"},cb);
        });
      }
    });
  Crawler.remoteMethod(
    'upload',
    {
      description: 'Uploads a script',
      accepts: [
        { arg: 'id', type: 'string', http: {source: 'path'}},
        { arg: 'req', type: 'object', http: { source:'req' } },
        { arg: 'res', type: 'object', http:{ source: 'res'} }
      ],
      returns: {
        arg: 'crawler', type: 'Crawler', root: true
      },
      http: {path: '/:id/script',verb: 'post'}
    }
  );
};

but the problem is when I run POST /Crawlers/:id/script, program freeze on container.upload(...) function and does not return anything. after a while, the request will be aborted due to timeout.

I found this solution on StackOverflow but the same problem happens there too.

What happens to upload function? are the parameters passed to upload correct? is there any workaround? is there any solution for uploading files other than loopback-component-storage?

(my node version is 6.7.0 and loopback 2)

Philbrick answered 6/10, 2016 at 6:57 Comment(0)
P
0

first of all, you should use body-parser middleware like this:

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

BTW files are sent in an array like this: fileObject.files[null]

Philbrick answered 8/10, 2016 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.