Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload files using nodejs and HAPI?

Can anyone tell me How to upload files Using nodejs and HAPI?

I am getting binary data inside the handler.

Here is my html code:

function sendFormFromHTML(form) {
        //form = $(".uploadForm").form;
        var formData = new FormData(form);
        formData.append('id', '123456'); // alternative to hidden fields
        var xhr = new XMLHttpRequest();
        xhr.open('POST', form.action, true);
        xhr.onload = function(e) { alert(this.responseText) };
        xhr.send(formData);
        return false;
    } 



<form method="post" id="uploadForm" action="http://localhost:3000/api/uploadfiles" enctype="multipart/form-data">
    <label for="upload">File (Binary):</label>
    <input type="file" name="upload" class="fileupload" /><br/>

    <input type="button" class="submit" value="Submit" onclick="sendFormFromHTML(this.form);"/>
  </form>

Here is My Nodejs code:

server.route({
    method: 'POST',
    path: '/api/uploadfiles',
    config: {        
        handler: currentposition.uploadFiles,
    }
});

uploadFiles:function(req,reply){
    console.log(req.payload);
}
like image 809
Realdheeraj Avatar asked Feb 17 '14 07:02

Realdheeraj


People also ask

Which libraries can be used for uploading files in node JS?

Multer is a node. js middleware which is used for handling multipart/form-data, which is mostly used library for uploading files.


1 Answers

For new readers, hapi already using multiparty uses pez to handle multipart post requests. From hapi documentation;

If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties.

Example;

server.route({
   method: 'POST',
   path: '/create',
   config: {
      payload:{
            maxBytes: 209715200,
            output:'stream',
            parse: true
      }, 
      handler: function (request, reply) {
          request.payload["htmlInputName"].pipe(fs.createWriteStream("test"));
      }
});
like image 136
ubaltaci Avatar answered Sep 20 '22 02:09

ubaltaci