Upload image with socketio-file-upload - node.js

I'm trying to upload files with socketio-file-upload, so far it does the job quite well, selecting the "upload image" button correctly uploads the file to the folder of my preference. My problem is that any button that clicks "Search for file" or "ClickHere" uploads the file without giving me the name of the file you select. What I want to achieve is
1.- Press the "Upload Image" button
2.- Show file name
3.- Upload the file to the selected folder by clicking the button "ClickHere"
Here is the code I am using
main.js
//Connection to the socket library
const socket = io();
//This is some classic socket.io event listening
socket.on('data', data => {
console.log(data);
});
//Here is our socketio-file-upload code
const uploader = new SocketIOFileUpload(socket);
//uploader.listenOnInput(document.getElementById('fileUpload'));
uploader.listenOnInput(document.getElementById('fileUpload'));
uploader.addEventListener('start', (event)=> {
event.file.meta.extension = 'csv';
});
document.getElementById('file_button').addEventListener('click', uploader.prompt, false);

From the Socket.IO File Upload documentation:
instance.listenOnSubmit(submitButton, input)
Like instance.listenOnInput(input), except instead of listening for the "change" event on the input element, listen for the "click" event of a button.
JavaScript:
instance.listenOnSubmit(document.getElementById("my_button"), document.getElementById("file_input"));
HTML:
<label>Upload File: <input type="file" id="file_input" /></label>
<button id="my_button">Upload File</button>
Try something like this:
main.js
//Connection to the socket library
const socket = io();
//This is some classic socket.io event listening
socket.on('data', data => {
console.log(data);
});
//Here is our socketio-file-upload code
const uploader = new SocketIOFileUpload(socket);
// When #file_button is clicked, the file in #fileUpload is uploaded.
uploader.listenOnSubmit(document.getElementById('file_button'), document.getElementById('fileUpload'));
uploader.addEventListener('start', (event)=> {
event.file.meta.extension = 'csv';
});

Related

How to get filepath of uploaded file to createReadStream

I am using Nodejs readStream.pipe(writeStream). How can I get the full path of the file I am uploading and assign it to createReadStream. I get only filename and When the file is in nodejs root directory it is fine no error but when I upload from anywhere else I get an error:
events.js:183
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open 'C:\Users\Esen\Documents\GitHub\gbmsturbo\nike.png'
I know that this happens because nike.png that I am uploading is not in "C:\Users\Esen\Documents\GitHub\gbmsturbo\".
It is inside this folder:
"C:\Users\Esen\Documents\GitHub\filestoupload"
I tried
function throwErrorDontCrash() {
process.on('uncaughtException', function (err) {
console.error(err.message)
})
}
and this prevents nodejs crash and uploads the file but with empty content (0 byte)
router.post('/upload', (req, res) => {
var filePath = req.body.file
var ext = path.extname(filePath)
var filename = path.basename(filePath, ext)
var newVerFilePath = "public/uploads/" + newVerFileName+ext
const readStream = fs.createReadStream(filePath)
throwErrorDontCrash()
const writeStream = fs.createWriteStream(newVerFilePath)
readStream.pipe(writeStream)
function throwErrorDontCrash() {
process.on('uncaughtException', function (err) {
//console.error(err.message)
})
}
and here is my form file
<form class="center" action="/upload" method="post">
<input id="file" type="file" name="file" required encrypt="multipart/form-data"/>
<input type="submit" value="UPLOAD">
I want filePath to include the directory path where ever the file is uploaded when user clicks on Choose or Browse button.
Currently, filePath gets only filename such as nike.png and my expectation is
to get "C:/Users/Esen/Documents/GitHub/filestoupload/nike.png"
it looks like you are writing an express app on nodejs. Your issue is here:
const readStream = fs.createReadStream(filePath);
I think that you believe this is how you "read" the file the user is uploading, but that's actually not possible - the "fs" module doesn't exist in the browser. The user navigating your website is uploading the image from their computer via a form, which means the image is coming in from the HTTP request (the req object), not from the file system.
(This can be confusing because in your case, you probably are running this express app locally on your machine, but it's easier to imagine it in production - the express app runs on a big server somewhere, and is a different computer than your user's computer, where the file being uploaded lives.)
Check out the related S.O. question How to upload, display and save images using node.js and express. Also, see the tutorial Upload Files or Images to Server using Nodejs.

Use the same socket.io connection in multiple HTML pages in node js

-Follwing is the jquery code I have written in my (dashboard.html) file
<script>
$(function(){
$("#username").hide();
var socket= io.connect();
$(document).on("click", ".help", function () {
alert( $(this).attr('id'));
socket.emit('help',{helper:$username.val(),requester:$(this).attr('id')});
});
});
---On clicking help button socket will emit an event "help" as you can see in the code.
---Following is the app.js file on server
io.sockets.on('connection',function(socket){
socket.on('help',function(data){
console.log('rohi is goood',data.helper);
socket.emit('loadList' , {helper:data.helper,requester:data.requester});
});
});
---On "help" event socket is emitting an event "loadList" in app.js file.
Now I want to use "loadList" event in some other html file like "chat.html".
The code I have written is as follows for chat.html.
<script>
$(function(){
// var socket= io.connect();
// var socket= io.connect('http://localhost:3000/', { 'force new //connection': true });
socket.on('loadList',function(data){
alert('inside help',$('#usernam').val());
console.log('tatai',$('#usernam').val());
if($('#usernam').val()== data.helper){
$('#chatList').append('<p>'+data.requester+'</p>'+'<button value="chat"></button>');
}
else if($('#usernam').val() == data.requester){
$('#chatList').append('<p>'+data.helper+'</p>'+'<button value="chat"></button>');
}
else {
alert('fuck off');
}
});
The above code is not working. Please tell me how can I use same socket connection in the chat.html file.(loadList event is not working).
As your question is not complete so i am assuming you want to know if socket.io connection can be used on different html pages . Yes you can access it on every html page of your application as long as you have one server on which socket.io is used .
Every time a new user comes a socket session is created for that particular user and that user can access any page of your application .

Uploading a file and sending it to the backend with React and Node

I need to upload a file in react and send it to the Node backend.
Since I never worked with uploading and sending files before, this is a little troubling for me.
So far I found this:
// this creates a React component that can be used in other components or
// used directly on the page with React.renderComponent
var FileForm = React.createClass({
// since we are starting off without any data, there is no initial value
getInitialState: function() {
return {
data_uri: null,
};
},
// prevent form from submitting; we are going to capture the file contents
handleSubmit: function(e) {
e.preventDefault();
},
// when a file is passed to the input field, retrieve the contents as a
// base64-encoded data URI and save it to the component's state
handleFile: function(e) {
var self = this;
var reader = new FileReader();
var file = e.target.files[0];
reader.onload = function(upload) {
self.setState({
data_uri: upload.target.result,
});
}
reader.readAsDataURL(file);
},
// return the structure to display and bind the onChange, onSubmit handlers
render: function() {
// since JSX is case sensitive, be sure to use 'encType'
return (
<form onSubmit={this.handleSubmit} encType="multipart/form-data">
<input type="file" onChange={this.handleFile} />
</form>
);
},
});
Source: https://fitacular.com/blog/react/2014/06/23/react-file-upload-base64/
But now I basically just end up with some sort of string. But I need to send that file via REST to my Express backend, which needs to save that file in CouchDB.
What is the best/easiest way to accomplish that?
If you are using body-parser, know that it handles json and url encoded forms, not multipart data !
You should use an other module.
For more infos, give a look at : File uploading with Express 4.0: req.files undefined

Chat App using Socket.io and Node.js

I am developing chat app using Node.js and Socket.io.
Here is my code.|
socket.js
var io = require('socket.io').listen(8001);
var http = require('http');
var url = require('url');
var fs = require('fs');
// open the socket connection
io.sockets.on('connection', function (socket) {
// listen for the chat even. and will recieve
// data from the sender.
socket.on('chat', function (data) {
// default value of the name of the sender.
var sender = 'unregistered';
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat Message By: ', name);
console.log('error ', err);
sender = name;
});
// broadcast data recieved from the sender
// to others who are connected, but not
// from the original sender.
socket.broadcast.emit('chat', {
msg : data,
msgr : sender
});
});
// listen for user registrations
// then set the socket nickname to
socket.on('register', function (name) {
// make a nickname paramater for this socket
// and then set its value to the name recieved
// from the register even above. and then run
// the function that follows inside it.
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "Hello " + name + '!',
msgr : "Mr.Server"
});
});
});
});
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var name = '';
var socket = io.connect('http://localhost:8001');
// at document read (runs only ones).
$(document).ready(function(){
// on click of the button (jquery thing)
// the things inside this clause happen only when
// the button is clicked.
$("button").click(function(){
// just some simple logging
$("p#log").html('Sent message: ' + $("input#msg").val());
// send message on inputbox to server
socket.emit('chat', $("input#msg").val() );
$("p#data_recieved").append("<br />\r\n" + name + ': ' + $("input#msg").val());
// then we empty the text on the input box.
$("input#msg").val('');
});
$("#btnSubmit").click(function(){
alert("Disconnected");
//socket.clients[kickedUserSocketId].onDisconnect();
socket.close();
});
// ask for the name of the user, ask again if no name.
while (name == '') {
name = prompt("What's your name?","");
}
// send the name to the server, and the server's
// register wait will recieve this.
socket.emit('register', name );
});
// listen for chat event and recieve data
socket.on('chat', function (data) {
// print data (jquery thing)
$("p#data_recieved").append("<br />\r\n" + data.msgr + ': ' + data.msg);
// we log this event for fun :D
$("p#log").html('got message: ' + data.msg);
});
socket.emit('forceDisconnect');
</script>
</head>
<body>
<input type="text" id="msg"></input>
<button>Click me</button>
<p id="log"></p>
<p id="data_recieved"></p>
</body>
<input id = "btnSubmit" type="submit" value="Disconnect"/>
</html>
I am running first socket.js from command prompt. After that, I am running .html file in browser 2 times. Now 2 users can chat via browsers. But when I am trying to put my .js file and .html file on server which I have created using FileZila and running .js file, it is running but when I am trying to run .html file on server side(In this case FileZila) , by giving the IP address and Port number of server it is not running. Can you tell me what is the problem?
This doesn't seem to be a nodejs-issue.
You have a server that should be reachable by IP with something like 'http://your.domain.or.ip:80'.
If you get a "can't connect" in your browser then make sure there is no firewall in its way and that port (in the example: 80) is reachable from your browser location (aka known as "your pc"). Please note that you have your socket-service on port 8001 and your web server maybe runs on a different port? Make sure both ports are open.
If you get a blank page, check the browser javascript error messages.
There is a chance that you forgot to upload the file 'socket.io.js' in that directory '/socket.io/'. Try to download that file directly to see if your server serves.

socket.io get data from onclick action then pass the data to other pages to execute the data

I want to create a page using node.js and socket.io.
There are two buttons inside the page, when I click one of them, it will change a variable which defines the animation-duration(I omit the CSS animation codes here).
When I open the same page on another web-browser and click one of the buttons, I hope to see the change in both of the webpages. I don't know how to write the code inside the socket.on('chat', function(data){???}); to make two pages communicate with each other.
Client side:
//socket.io codes--
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://localhost:3000');
socket.on('chat', function (data)
{
function change_position(data)
{
document.getElementById("animation1").style.WebkitAnimationDuration=data;
}
});
</script>
.....
//action--
<body>
<button id="1b" type="button" style="position:absolute; left:377px; top:220px;" value="2s"; onclick="change_position(value)"> - 1 - </button>
<button id="2b" type="button" style="position:absolute; left:477px; top:220px;" value="15s"; onclick="change_position(value)"> - 2 - </button>
</body>
server side:
var io = require('socket.io'),
connect = require('connect');
var app = connect().use(connect.static('public')).listen(3000);
var chat_room = io.listen(app);
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
chat_room.sockets.emit('chat', data);
});
});
If your want a message to propagate to all clients/sockets, in your server you should have something like:
chat_room.sockets.on('connection', function (socket) {
socket.on('chat', function (data) {
socket.broadcast.emit('chat', data);
socket.emit('chat',data);
});
});
The line socket.emit('chat',data); allows you to send the message back also to the sender of it, because broadcast will send it all other sockets.
Of course, you could ommit that line and handle the message sending logic in the client; i.e. adding some JavaScript code that makes the changes you want just after sending the message to the server.
You can emit on your client using socket.emit('message', data). Then on the server get it with chat_room.socket.on('message', data). Emit it to the clients using chat_room.sockets.emit('message', data).

Resources