koajs / joi-router

Configurable, input and output validated routing for koa
MIT License
450 stars 96 forks source link

ctx.request.parts #51

Closed willin closed 5 years ago

willin commented 7 years ago

like #44

handler: async (ctx) => {
      const parts = ctx.request.parts;
      const file = await parts;
      const ext = file.filename.split('.').pop();
      if (fileExt.indexOf(ext) === -1) {
        ctx.status = 400;
        return;
      }

// passed in, but cannot get

      const type = parts.field.type;
      const types = ['sth'];
      if (types.indexOf(type) === -1) {
        ctx.status = 400;
        return;
      }

      const filename = `sth`;
      const result = await createBlockBlobFromStream(type, filename, file);

      ctx.status = 200;
      ctx.body = {status: 1, data: {filename}};
    }

and i changed it to:

handler: async (ctx) => {
      const parts = ctx.request.parts;
      let part;
      let file;
      /* eslint no-cond-assign:0, no-await-in-loop:0 */
      while (part = await parts) {
        if (part.filename) {
          file = part;
        }
        part.resume();
      }
      const ext = file.filename.split('.').pop();
      if (fileExt.indexOf(ext) === -1) {
        ctx.status = 400;
        return;
      }

// can get form-data fields

      const type = parts.field.type;
      const types = ['sth'];
      if (types.indexOf(type) === -1) {
        ctx.status = 400;
        return;
      }
      const filename = `sth`;

// cannot upload to oss service, hanging without any err

      const result = await createBlockBlobFromStream(type, filename, file);

// never print
console.log('123');

      ctx.status = 200;
      ctx.body = { status: 1, data: { filename } };
    }

p.s.

exports.createBlockBlobFromStream = (container, filename, blob) => {
  const deferred = {};
  deferred.promise = new Promise((resolve, reject)=>{
    deferred.resolve = resolve;
    deferred.reject = reject;
  });
  blob.on('error', (err) => {
    deferred.reject(err);
  });
  blob.pipe(blobService.createWriteStreamToBlockBlob(container, filename));
  blob.on('end', () => {
    deferred.resolve(1);
  });
  return deferred.promise;
};
aheckmann commented 5 years ago

Closing due to inactivity. Please reopen with a reproducible example if the issue persists.