A simple solution for file upload in hapi.js. Here we will show you how to upload and download the file of any extension in a very simple manner.<br>
<a title="Hapi file upload download repo link" href="https://github.com/pandeysoni/Hapi-file-upload-download" target="_blank">Hapi file upload download repo link</a><br>
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.</p>
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 function will read file which we uploaded and write in respective mentioned directory. See here
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);
});
});
};
Here we used checkFileExist function, which will create directory if it does not exist. See here
var checkFileExist = function() {
fs.exists(Config.publicFolder, function(exists) {
if (exists === false) fs.mkdirSync(Config.publicFolder);
fs.exists(Config.MixFolder, function(exists) {
if (exists === false) fs.mkdirSync(Config.MixFolder);
});
});
};
We need to set content type to download the file
Set here content-type according to extension
switch (ext) {
case "pdf":
contentType = 'application/pdf';
break;
case "ppt":
contentType = 'application/vnd.ms-powerpoint';
break;
case "pptx":
contentType = 'application/vnd.openxmlformats-officedocument.preplyentationml.preplyentation';
break;
case "xls":
contentType = 'application/vnd.ms-excel';
break;
case "xlsx":
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case "doc":
contentType = 'application/msword';
break;
case "docx":
contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case "csv":
contentType = 'application/octet-stream';
break;
default:
reply.file(path);
No comments:
Post a Comment