javascript 如何使用 nodejs 和 HAPI 上传文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21823379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:46:13  来源:igfitidea点击:

How to upload files using nodejs and HAPI?

javascriptnode.jsexpresshapijs

提问by Realdheeraj

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

谁能告诉我如何使用 nodejs 和 HAPI 上传文件?

I am getting binary data inside the handler.

我在处理程序中获取二进制数据。

Here is my html code:

这是我的 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>

Here is My Nodejs code:

这是我的 Nodejs 代码:

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

uploadFiles:function(req,reply){
    console.log(req.payload);
}

采纳答案by Realdheeraj

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

最后我得到了使用 HAPI 上传大文件的解决方案,感谢 Roman。

Here is the solution:

这是解决方案:

server.js code

server.js 代码

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)

            });

    }
}

回答by ubaltaci

For new readers, hapi already using multipartyuses pezto handle multipart post requests. From hapi documentation;

对于新读者,hapi已经使用多方使用pez来处理多部分发布请求。来自 hapi 文档;

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.

如果有效负载是“multipart/form-data”并且解析为真,则字段值以文本形式呈现,而文件以流形式提供。来自“multipart/form-data”上传的文件流也将具有包含文件名和标题属性的属性 hapi。

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

回答by Realdheeraj

You can visit for working code in https://github.com/pandeysoni/Hapi-file-upload-download

您可以访问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);

        });
    });
};