Last active
August 12, 2020 14:25
-
-
Save elhardoum/dc97a68c0cc2d4e5682c7a81d277259e to your computer and use it in GitHub Desktop.
Handle file uploads in node.js without express
This file contains hidden or 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
// call fileUploadRequestHandler( req, res ) from http.createServer callback context | |
// change ./files references to your files directory name | |
async function fileUploadRequestHandler( req, res ) | |
{ | |
const fs = require(fs), path = require('path') | |
// update the file name/ext here to a random or dynamic one (e.g supplied from querystring) | |
const filename = 'example.txt' | |
// update 10e6 for more/less than 10 MB post size | |
const file_buffer = await getRequestInput( req, 10e6 ) | |
if ( ! file_buffer || ! file_buffer.length ) | |
return res.writeHead(400), res.end() | |
// initiate uploads folder | |
fs.existsSync('./files') || fs.mkdirSync('./files') | |
try { | |
await fs.writeFile(path.join('./files', filename), file_buffer, 'binary', err => | |
{ | |
if ( err ) throw new Error(err) | |
}) | |
} catch (error) { | |
console.log( '[ERROR] file upload ended with an error', error ) | |
return res.writeHead(500), res.end() | |
} | |
return res.end(filename) | |
} | |
function getRequestInput( request, limit ) | |
{ | |
return new Promise(resolve => | |
{ | |
let body = Buffer.from('') | |
request.on('data', data => | |
{ | |
body = Buffer.concat([ body, Buffer.from(data) ]) | |
body.length > limit && request.connection.destroy() | |
}) | |
request.on('end', () => resolve(body)) | |
}) | |
} |
This file contains hidden or 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 input = document.querySelector('input[type=file]') | |
const file = input.files[0] | |
const xhr = new XMLHttpRequest | |
xhr.open('POST', 'http://your-server.co/files-handler', true) | |
xhr.setRequestHeader('Content-Type', 'application/octate-stream') | |
xhr.onreadystatechange = () => | |
{ | |
if ( 4 == xhr.readyState ) { | |
if ( 200 == xhr.status ) { | |
console.log('uploaded to', xhr.responseText) | |
} else { | |
console.log('error uploading file') | |
} | |
} | |
} | |
xhr.send(file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment