谁能告诉我如何使用nodejs和HAPI上传文件?
我在处理程序中获取二进制数据。
这是我的html代码:
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>
这是我的Nodejs代码:
server.route({ method: 'POST', path: '/api/uploadfiles', config: { handler: currentposition.uploadFiles, } }); uploadFiles:function(req,reply){ console.log(req.payload); }
最后,我得到了使用HAPI上传大型文件的解决方案,并感谢Roman。
解决方法如下:
server.js代码
server.route({ method: 'POST', path: '/api/uploadfiles', config: { payload:{ maxBytes:209715200, output:'stream', parse: false }, handler: currentposition.uploadFiles, } });
处理程序代码:
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) }); } }