从其他模型上传文件

从其他模型上传文件

本文介绍了环回-从其他模型上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

容器:处理文件上传并在回送资源管理器中正常工作.

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

抓取工具:有多个属性.属性之一是script,用户可以将脚本文件上传到该模型.

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

但是问题是当我运行POST /Crawlers/:id/script时,程序冻结了container.upload(...)函数,并且不返回任何内容.一段时间后,该请求将因超时而中止.

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.

我在StackOverflow上找到了此解决方案,但是同样的问题也在那里发生.

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

upload功能会如何?传递给upload的参数正确吗?有什么解决方法吗?除了loopback-component-storage以外,还有什么其他上传文件的解决方案吗?

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?

(我的节点版本为6.7.0,环回2)

(my node version is 6.7.0 and loopback 2)

推荐答案

首先,您应该使用body-parser中间件,如下所示:

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

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

BTW文件以如下数组形式发送:fileObject.files[null]

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

这篇关于环回-从其他模型上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 22:28