Created
September 14, 2019 18:50
-
-
Save midnightcodr/0e569b6f20b2ddd8b5a376a4f7e5a320 to your computer and use it in GitHub Desktop.
hapi-js-file-upload-with-content-type-detection-demo.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Hapi = require('@hapi/hapi') | |
const Joi = require('@hapi/joi') | |
const fileType = require('file-type') | |
const stream = require('stream') | |
const Readable = stream.Readable | |
const port = 5000 | |
const server = Hapi.server({ | |
port | |
}) | |
server.route({ | |
path: '/docs', | |
method: 'POST', | |
options: { | |
validate: { | |
payload: { | |
upfile: Joi.object() | |
.type(Readable) | |
.required() | |
} | |
}, | |
payload: { | |
output: 'stream', | |
parse: true | |
} | |
}, | |
async handler (request, h) { | |
const { upfile } = request.payload | |
let st | |
try { | |
st = await fileType.stream(upfile) | |
} catch (err) { | |
console.error(err) | |
return new Error('Failure') | |
} | |
return st.fileType | |
} | |
}) | |
const init = async () => { | |
await server.start() | |
console.log(`server started at ${server.info.uri}`) | |
} | |
init() | |
// To test | |
// curl -F 'upfile=@/path/to/afile.ext' http://localhost:5000/docs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment