谁能告诉我如何使用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>
这是My Nodejs代码:
server.route({
method: 'POST',
path: '/api/uploadfiles',
config: {
handler: currentposition.uploadFiles,
}
});
uploadFiles:function(req,reply){
console.log(req.payload);
}
答案 0 :(得分:40)
对于新读者,hapi 已经使用多方使用pez来处理多部分帖子请求。来自hapi文档;
如果有效负载是“multipart / form-data&#39;并且parse为true,字段值以文本形式呈现,而文件以流形式提供。来自&#39; multipart / form-data&#39;的文件流upload还将包含一个包含filename和headers属性的属性hapi。
实施例
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"));
}
});
答案 1 :(得分:5)
您可以访问https://github.com/pandeysoni/Hapi-file-upload-download
中的工作代码/*
* upload file
*/
exports.uploadFile = {
payload: {
maxBytes: 209715200,
output: 'stream',
parse: false
},
handler: function(requset, reply) {
var form = new multiparty.Form();
form.parse(requset.payload, function(err, fields, files) {
if (err) return reply(err);
else upload(files, reply);
});
}
};
/*
* upload file function
*/
var upload = function(files, reply) {
fs.readFile(files.file[0].path, function(err, data) {
checkFileExist();
fs.writeFile(Config.MixInsideFolder + files.file[0].originalFilename, data, function(err) {
if (err) return reply(err);
else return reply('File uploaded to: ' + Config.MixInsideFolder + files.file[0].originalFilename);
});
});
};
答案 2 :(得分:3)
最后,我得到了使用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)
});
}
}