How to upload files using nodejs and HAPI?

19,265

Solution 1

Finally I got the solution to upload the large files using HAPI and Thanks to Roman.

Here is the solution:

server.js code

server.route({
    method: 'POST',
    path: '/api/uploadfiles',
    config: {
          payload:{
                maxBytes:209715200,
                output:'stream',
                parse: false
          }, 
          handler: currentposition.uploadFiles,
    }
});

Handler code:

var currentpositionApi = {

    fs : require('fs'),
    multiparty: require('multiparty'),
    uploadFiles:function(req,reply){
         var form = new currentpositionApi.multiparty.Form();
            form.parse(req.payload, function(err, fields, files) {
                currentpositionApi.fs.readFile(files.upload[0].path,function(err,data){
                    var newpath = __dirname + "/"+files.upload[0].originalFilename;
                    currentpositionApi.fs.writeFile(newpath,data,function(err){
                        if(err) console.log(err);
                        else console.log(files)
                    })
                })
                console.log(files)

            });

    }
}

Solution 2

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"));
      }
});
Share:
19,265

Related videos on Youtube

Realdheeraj
Author by

Realdheeraj

Updated on September 14, 2022

Comments

  • Realdheeraj
    Realdheeraj over 1 year

    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);
    }
    
    • Roman Liutikov
      Roman Liutikov about 10 years
      I'm just telling that you can use the parser. Try multipraty FormData parser.
  • GregT
    GregT over 9 years
    This approach is duplicating effort that the HAPI framework already handles for you. The parse: true approach below is a better solution.
  • Eran Hammer
    Eran Hammer over 9 years
    You really have no reason to handle the multipart parsing yourself. Also, the way you are using multiparty is awkward at best, having it write data to files just so you can read those files back (and the write them again?!).
  • Daniel M
    Daniel M about 5 years
    @GregT I could be mistaken, but I think handling multiple part on your own is warranted when you are dealing with very large file payloads, you want to avoid loading them into memory, and you want a true stream. The Hapi docs state: "Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez)"
  • GregT
    GregT about 5 years
    @DavidM its an interesting use case, but it was not what the original question wanted to solve. Fair point though.