Last active
October 24, 2021 02:59
-
-
Save companje/179d98b7e15122f2ed4a to your computer and use it in GitHub Desktop.
Upload using socket.io-stream
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
/////////////////////////// | |
/// Server NodeJS | |
////////////////////////// | |
var express = require('express'); | |
var app = express(); | |
var http = require('http').Server(app); | |
var io = require('socket.io')(http); | |
var ss = require('socket.io-stream'); | |
var path = require('path'); | |
var fs = require('fs'); | |
io.of('/user').on('connection', function(socket) { | |
console.log("connection"); | |
ss(socket).on('profile-image', function(stream, data) { | |
console.log("saving..."); | |
stream.pipe(fs.createWriteStream("copy.png")); | |
}); | |
}); | |
app.use(express.static(__dirname, '/')); | |
http.listen(8080, function(){ | |
console.log('listening on *:8080'); | |
}); | |
///////////////////////// | |
// Client (NodeJS) | |
///////////////////////// | |
var io = require('socket.io-client'); | |
var ss = require('socket.io-stream'); | |
var fs = require('fs'); | |
var socket = io.connect('http://localhost:8080/user'); | |
var stream = ss.createStream(); | |
var filename = 'image.png'; | |
ss(socket).emit('profile-image', stream, {name: filename}); | |
fs.createReadStream(filename).pipe(stream); | |
///////////////////////////////// | |
// Client (Browser) | |
//////////////////////////////// | |
<input id="file" type="file" /> | |
<script src="jquery-2.1.1.js"></script> | |
<script src="socket.io/socket.io.js"></script> | |
<script src="socket.io-stream.js"></script> | |
<script> | |
$(document).ready(function() { | |
$(function() { | |
var socket = io.connect('http://localhost:8080/user'); | |
socket.on("connect",function() { | |
console.log("on connect"); | |
}) | |
$('#file').change(function(e) { | |
console.log('uploading...',file) | |
var file = e.target.files[0]; | |
var stream = ss.createStream(); | |
var blobStream = ss.createBlobReadStream(file); | |
blobStream.on('data', function(chunk) { | |
console.log('data chunk.length:',chunk.length); | |
}); | |
blobStream.on('end', function() { | |
console.log('end'); | |
}); | |
ss(socket).emit('profile-image', stream); | |
blobStream.pipe(stream); | |
}); | |
}); | |
}); | |
</script> |
Hey,
I tried this code and getting an error while dealing with the browser side coding
in this line ' var stream = ss.createStream(); ' ss is not defined.
Mr. Rick Companje please help me out on this.
TIA.
Regards
Inderjit Bedi.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
I am new to node js. I tried this code. Getting an error at line var stream = ss.createStream();
that ss is not defined. How can I resolve this issue. please help me.