Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save midnightcodr/0e569b6f20b2ddd8b5a376a4f7e5a320 to your computer and use it in GitHub Desktop.
Save midnightcodr/0e569b6f20b2ddd8b5a376a4f7e5a320 to your computer and use it in GitHub Desktop.
hapi-js-file-upload-with-content-type-detection-demo.js
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