Last active
June 12, 2019 10:34
-
-
Save arturi/624b70c681be7c703379478cbdbba0e5 to your computer and use it in GitHub Desktop.
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
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