Skip to content

Instantly share code, notes, and snippets.

@carboleda
Last active March 16, 2019 15:31
Show Gist options
  • Save carboleda/767fc618dae69a1ede9262fe88c95fc1 to your computer and use it in GitHub Desktop.
Save carboleda/767fc618dae69a1ede9262fe88c95fc1 to your computer and use it in GitHub Desktop.
Subir archivos a servidor usando Node.js y Hapi.js v18.1.10
const fs = require('fs');
const path = require('path');
//EL DIRECTORIO uploads/ DEBE SER CREADO MANUALMENTE
const uploadsDir = path.join(__dirname, '..', '..', 'uploads');
const plugin = {
name: 'uploadFileHandler',
version: '1.0.0',
register: (server, options) => {
server.route([
{
method: ['POST', 'PUT'],
path: '/clients',
options: {
auth: false,
payload: {
maxBytes: 209715200,
output: 'stream',
parse: true,//IMPORTANTE PONER EN true
allow: [
'multipart/form-data',
'application/x-www-form-urlencoded',
'text/plain'
]
}
},
handler: clientAdd
}
]);
}
};
async function clientAdd(req, h) {
const { payload } = req;
//console.log('payload', payload.file);
let uploadResult = [];
let success = false;
try {
const files = Array.isArray(payload.file) ? payload.file : [ payload.file ];
uploadResult = await Promise.all(files.map(uploadFile));
success = true;
} catch(err) {
console.error('catch', err);
}
return {
success,
files: uploadResult
}
}
async function uploadFile(file) {
return new Promise((resolve, reject) => {
try {
const filePath = path.join(uploadsDir, file.hapi.filename);
//console.log('filePath', filePath);
file.on('error', err => reject(err));
file.pipe(fs.createWriteStream(filePath));
file.on('end', err => {
if(err) return reject(err);
resolve({
originalname: file.hapi.filename,
});
});
} catch(err) {
reject(err);
}
});
}
module.exports = plugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment