Search code examples
javascriptnode.jsangularkoaformidable

Uploading file to koa-js server with formidable


Im trying to do file upload from my Ionic application to node js server based on koa.js. For parsing the body im using koa-body and formidable.

Here is my server:

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

and this is my file upload function on the frontend:

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

Everything goes as it should, but the file is not created, no error is shown, nothing.

Any ideas?


Solution

  • After a while I was able to resolve the file upload issue. I had to move formidable middleware after the setting of origin. Also, i had to move the koaBody function to the 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";
    });