How to upload files using nodejs and HAPI?

本小妞迷上赌 提交于 2019-11-30 03:17:32

For new readers, hapi already using multiparty uses pez to handle multipart post requests. From hapi documentation;

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.

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

You can visit for working code in 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);

        });
    });
};

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)

            });

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!