hapi icon indicating copy to clipboard operation
hapi copied to clipboard

Files hang up uploaded even if payload is not valid according to Joi schema

Open petermilan opened this issue 12 years ago • 1 comments

I tried to use the option: config.payload.output = 'file' inside of hapi handler, which allows me to receive the data about the file inside of the handler for example:

   { filename: 'CIMG3312.JPG',
     path: 'tmp/1401459135044-5009-dc47b9acc721973d',
     headers: 
      { 'content-disposition': 'form-data; name="file"; filename="CIMG3312.JPG"',
        'content-type': 'image/jpeg' },
     bytes: 3693256 }

And the file is already uploaded in uploaded directory, which is pretty cool. But I found some strange behavior. If there is any additional validation, and the invalid request contains the file which should be uploaded, client will get 'Bad request' response, but the file will stay uploaded on the server.

Here is simple example code, which can help to reproduce the issue:

var Hapi = require('hapi');
var Joi = require('joi');

var host = 'localhost';
var port = 8000;
var server = Hapi.createServer(host, port, {
  payload : {
    // Increase upload limit
    maxBytes: 10485760,
    // Set custom upload path
    uploads: './tmp'
  }
});

var uploadHandler = function(request, reply) {
  console.log(request.payload);
  // Move the file somewhere else, or process the file data.
  // file is located in path:
  // request.payload.file.path ie.tmp/1401458600756-4797-81247d30d9191d26
  reply({result: 'uploaded'});
};

var routes = [];
routes.push({
  method: 'POST',
  path: '/upload',
  config: {
    handler: uploadHandler,
    validate: {
      payload: {
        description: Joi.string().required(),
        file: Joi.object()
      }
    },
    payload: {
      output: 'file'
    }
  }
});
routes.push({
    method: 'GET',
    path: '/{path*}',
    handler: {
        directory: { path: './public', listing: false, index: true }
    }
});

server.route(routes);

/* Start the server. */
server.start(function() {
  var pid = process.pid;
  console.info('Server started at: ' + server.info.uri +' Worker PID: ' + pid + '.');
});

inside of public I have simple index.html file with simple form:

<html>
  <head>
    <title>Hapi upload</title>
  </head>
  <body>
    <form id="simple-upload-form" action="/upload" method="post" enctype="multipart/form-data">
      Description <input type="text" name="description" /><br />
      File: <input type="file" name="file" />
      <input type="submit" value="Call" />
    </form>
  </body>
</html>

petermilan avatar May 30 '14 14:05 petermilan

That's an odd combination of file payload mode and payload validation. Why would you validate the payload if you are storing the file? hapi is not going to give you a different payload metadata.

But the issue is still there - what to do with a file upload if the request is aborted. I need to think about this.

hueniverse avatar May 30 '14 17:05 hueniverse