Skip to content

Instantly share code, notes, and snippets.

@memandip
Created July 25, 2019 12:18
Show Gist options
  • Save memandip/2684036c1890d5148b5d977086af0615 to your computer and use it in GitHub Desktop.
Save memandip/2684036c1890d5148b5d977086af0615 to your computer and use it in GitHub Desktop.
Ajax based file upload in nodejs with express-fileupload
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Node JS File Upload</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input type="file" name="inputFile" multiple />
<input type="submit" />
</form>
</body>
<script>
let form = document.querySelector('form')
form.addEventListener('submit', function (e) {
e.preventDefault()
let self = this
fetch('/', {
method: 'post',
body: new FormData(self)
})
.then(res => alert('file uloaded'))
.catch(err => alert('something went wrong'))
})
</script>
</html>
const app = require('express')()
const path = require('path')
const fileUpload = require('express-fileupload')
app.use(fileUpload())
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './index.html'))
})
app.post('/', (req, res) => {
const { inputFile } = req.files
if (inputFile) {
let filename = inputFile.name
inputFile.mv(path.join(__dirname, `uploads/${filename}`), (err) => {
if (err) res.send(500).send(err)
res.json({ success: true, message: 'File uploaded.' })
})
} else {
res.redirect('/')
}
})
app.listen(8001, () => 'Express server running on port 8001')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment