代码之家  ›  专栏  ›  技术社区  ›  Michal Takáč

将文件上传到koa js服务器

  •  0
  • Michal Takáč  · 技术社区  · 7 年前

    我正在尝试从我的Ionic应用程序上传文件到基于koa的node js服务器。js。对于解析身体im使用koa身体和强大。

    这是我的服务器:

    this.app.use(formidable());
    
    this.app.use(koaBody({
      formidable:{
          uploadDir: __dirname + '/uploads', // directory where files will be uploaded
          keepExtensions: true, // keep file extension on upload
          multiples: true
      },
      multipart: true,
      urlencoded: true,
      formLimit: '5mb',
    }));
    
    this.app.use(_.post('/wish/photo/upload', async (ctx, next) => {
          //ctx.body = JSON.stringify(ctx.request);
          next();
        }));
    

    这是我在前端的文件上传功能:

    uploadFromPc(files, parameters){
        let headers = new Headers();
        let formData = new FormData();
        Array.from(files).forEach(file => formData.append('photo', file));
        let options = new RequestOptions({ headers: headers });
        //options.params = parameters;
        return this.http.post(EnvVariables.apiEndpoint + 'wish/photo/upload', formData, options)
                 .subscribe(response => console.log(response))
    }
    

    一切正常,但文件没有创建,没有显示错误,什么都没有。

    有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Michal Takáč    7 年前

    过了一段时间,我终于解决了文件上传问题。在原点设置之后,我不得不移动强大的中间件。此外,我必须将koaBody函数移到post action

    router.post('/wish/photo/upload', koaBody({
      formidable: {
          uploadDir: __dirname + '/uploads', // directory where files will be uploaded
          keepExtensions: true, // keep file extension on upload
          multiples: true,
      },
      multipart: true,
      urlencoded: true,
      formLimit: '5mb',
    }), (ctx, next) => {
      ctx.body = "Success";
    });