Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  120] [ 4]  / answers: 1 / hits: 19982  / 10 Years ago, mon, february 17, 2014, 12:00:00

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);
}

More From » node.js

 Answers
22

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)

});

}
}

[#72487] Saturday, February 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;