Last active
May 3, 2023 20:31
-
-
Save ObjSal/0e6281ec5f2f920d3edf5ad48e463d3c to your computer and use it in GitHub Desktop.
Upload files to Node.js without form or third-party frameworks
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 http = require('http'); | |
const fs = require('fs') | |
let port = 3000 | |
http.createServer((req, response) => { | |
/** | |
* `/` loads index.html | |
*/ | |
if (req.url == '/' && req.method.toLowerCase() == 'get') { | |
response.setHeader('Content-Type', 'text/html') | |
const stream = fs.createReadStream(`${__dirname}/zindex.html`) | |
// No need to call res.end() because pipe calls it automatically | |
stream.pipe(response) | |
} | |
/** | |
* `/fileUpload` only works with POST | |
* Saves uploaded files to the root | |
*/ | |
else if (req.url == '/fileUpload' && req.method.toLowerCase() == 'post') { | |
response.setHeader('Content-Type', 'application/json') | |
let contentLength = parseInt(req.headers['content-length']) | |
if (isNaN(contentLength) || contentLength <= 0 ) { | |
response.statusCode = 411; | |
response.end(JSON.stringify({status: "error", description: "No File"})) | |
return | |
} | |
// Try to use the original filename | |
let filename = req.headers['filename'] | |
if (filename == null) { | |
filename = "file." + req.headers['content-type'].split('/')[1] | |
} | |
const filestream = fs.createWriteStream(`${__dirname}/${filename}`) | |
filestream.on("error", (error) => { | |
console.error(error) | |
response.statusCode = 400; | |
response.write(JSON.stringify({status: "error", description: error})) | |
response.end() | |
}) | |
// Write data as it comes | |
req.pipe(filestream) | |
req.on('end', () => { | |
filestream.close(() => { | |
response.end(JSON.stringify({status: "success"})) | |
}) | |
}) | |
} | |
/** | |
* Error on any other path | |
*/ | |
else { | |
response.setHeader('Content-Type', 'text/html') | |
response.end("<html><body><h1>Page Doesn't exist<h1></body></html>") | |
} | |
}).listen(port, () => { | |
console.log(`Server running at http://localhost:${port}/`); | |
}) |
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
<html> | |
<head> | |
<script> | |
const handleImageUpload = event => { | |
const file = event.target.files[0] | |
if (file == null) return | |
fetch('/fileUpload', { | |
headers: { | |
'filename': file.name | |
}, | |
method: 'POST', | |
body: file | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
console.log(data) | |
}) | |
.catch(error => { | |
console.error(error) | |
}) | |
} | |
function init() { | |
document.getElementById('fileUpload').addEventListener('change', event => { | |
handleImageUpload(event) | |
}) | |
} | |
</script> | |
</head> | |
<body onload="init()"> | |
<!-- input type="file" id="fileUpload" accept="image/*" / --> | |
<input type="file" id="fileUpload" /> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment