loopback - Upload files from another model

强颜欢笑 提交于 2019-12-08 13:09:10

问题


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)


回答1:


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]



来源:https://stackoverflow.com/questions/39889471/loopback-upload-files-from-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!