如何使用NodeJS和HAPI上传文件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (609)

有人能告诉我如何使用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);
}
提问于
用户回答回答于
/*
 * 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);

        });
    });
};
用户回答回答于
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"));
      }
});

扫码关注云+社区

领取腾讯云代金券