Search code examples
javascriptnode.jspdfasyncfileuploadhapi.js

Hapi.js file upload how do I grab the file so I could use imageMagick command line tool on it


I changed the code to output a file instead of a stream. IT provides me the the tmp path and when I use fs.readFile the data when converted to string is

fileUpload=Resume_BrianInoa.pdf

I am posting a file to hapijs server this is my route handling the post:

  server.route({
   method: 'POST',
   path: '/convert',
   config: {
        payload: {
           output:'file',
           maxBytes:209715200,
            parse: false,
            allow: 'application/x-www-form-urlencoded'
        },
        handler:function (request, reply) {

           console.log('path : ' + request.payload.path);
         //   request.payload["fileUpload"].pipe(fs.createWriteStream("test"));
             fs.readFile(request.payload.path, function (err, data) {
                if(err)
                   console.error(err);
                else
                   console.log(data.toString());
               // I want to rewrite the file to a new folder here 
               // Then convert it using imageMagick's command line tool
               //  var newPath = __dirname + "/uploads/" + "newFile.txt" ;
               //  fs.writeFile(newPath, data, function (err) {
               //    console.log(err);
               //    reply('done');
               //  });

             });
          }
   },

This is my request.payload

path : /tmp/1415580285921-24240-2cc7987f4fd124ac

I actually checked my /tmp/ folder and opened it the only thing that the file

/tmp/1415580285921-24240-2cc7987f4fd124ac

has is fileUpload=Resume_BrianInoa.pdf The file does not get uploaded correctly

html code for my form

<form action="./convert" method="post">
<input type="file" name="fileUpload" id="fileUpload" enctype="multipart/form-data" class="form-control">
<button class="btn">Submit</button>
</form>

Solution

  • just to sum it up your html should be something like this -

    <form action="./convert" method="POST" enctype="multipart/form-data">
        <input type="file" name="fileUpload" id="fileUpload" class="form-control"> 
        <button class="btn">Submit</button>
    </form>
    

    and your hapi route

       server.route({
           method: 'POST',
           path: '/convert',
           config: {
                payload: {
                   output: 'file',
                   maxBytes: 209715200,
                   //allow: 'multipart/form-data',
                   parse: true //or just remove this line since true is the default
                },
                handler:function (request, reply) {   
                   console.log('fileUpload path : ' + request.payload.fileUpload.path);
                }
           },
       });