Skip to content

Instantly share code, notes, and snippets.

@memandip
Last active July 26, 2019 12:26
Show Gist options
  • Save memandip/3fdda38177faaffdfaf1b6025474b7e9 to your computer and use it in GitHub Desktop.
Save memandip/3fdda38177faaffdfaf1b6025474b7e9 to your computer and use it in GitHub Desktop.
Send file with websocket
<!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 WebSocket Upload</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input type="file" id="inputFile" name="inputFile" onchange="sendFile()" />
<input type="submit" />
</form>
</body>
<script>
let ws = new WebSocket('ws://localhost:8001/socket')
function sendFile() {
let file = document.getElementById('inputFile').files[0]
let reader = new FileReader()
reader.addEventListener('loadend', function () {
})
reader.addEventListener('load', function (e) {
rawData = e.target.result
ws.send(rawData)
})
reader.readAsArrayBuffer(file)
}
</script>
</html>
const WebSocket = require('ws')
const fs = require('fs')
const path = require('path')
const readChunk = require('read-chunk')
const fileType = require('file-type')
const app = require('express')()
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './index.html'))
})
app.listen(8081, () => console.log('Express server running on port 8081'))
ws = new WebSocket.Server(
{ port: 8001, path: '/socket' },
() => console.log('WS running on port 8001')
)
ws.on('connection', async (socket, req) => {
socket.on('message', function (message) {
let filePath = path.join(__dirname, 'myBinaryFile')
let writeStream = fs.createWriteStream(filePath)
writeStream.write(message)
writeStream.on('finish', () => {
const buffer = readChunk.sync(filePath, 0, fileType.minimumBytes)
let fileInfo = fileType(buffer)
let { ext } = fileInfo
fs.rename(filePath, `${filePath}.${ext}`, err => console.log('err', err))
})
writeStream.end()
})
socket.on('close', function () {
console.log('socket terminated')
this.terminate()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment