Skip to content

Instantly share code, notes, and snippets.

@arturi
Last active June 12, 2019 10:34
Show Gist options
  • Save arturi/624b70c681be7c703379478cbdbba0e5 to your computer and use it in GitHub Desktop.
Save arturi/624b70c681be7c703379478cbdbba0e5 to your computer and use it in GitHub Desktop.
var formidable = require('formidable')
var http = require('http')
http.createServer(function (req, res) {
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000 // 30 days
/** add other headers as per requirement */
}
if (req.method === 'OPTIONS') {
res.writeHead(204, headers)
res.end()
return
}
if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
// parse a file upload
var form = new formidable.IncomingForm()
form.uploadDir = "uploads"
form.keepExtensions = true
form.multiples = true
form.parse(req, function (err, fields, files) {
const filePath = files[Object.keys(files)[0]].path
if (err) {
res.writeHead(200, headers)
res.write(JSON.stringify(err))
return res.end()
}
res.writeHead(200, headers)
res.write(JSON.stringify({
body: { fields, files },
url: filePath,
status: 200
}))
console.log(JSON.stringify({fields, files}))
return res.end()
})
}
}).listen(5000, () => {
console.log('server started on:', 'localhost:5000/upload')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment