我正在使用nodejs创建一个聊天室。我为此目的使用express,socket.io和http。我正在寻找通过http服务器进行文件共享的选项。首选的文件格式是图像文件(.jpg或.png)和文本文件。但我无法做到。我尝试使用html的input
标记,但它没有将任何文件上传到服务器。
这是我的服务器端代码(server.js)
var express = require("express")
, app = express()
, http = require("http").createServer(app)
, bodyParser = require("body-parser")
, io = require("socket.io").listen(app.listen(3000))
, _ = require("underscore");
const file = require('express-fileupload');
app.use(file());
var participants = [];
app.set("ipaddr", "127.0.0.1");
app.set("port", 8080);
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
app.use(express.static("public", __dirname + "/public"));
app.use(bodyParser.json());
app.get("/", function(request, response) {
response.render("index");
});
app.post("/message", function(request, response) {
var message = request.body.message;
if(_.isUndefined(message) || _.isEmpty(message.trim())) {
return response.json(400, {error: "Message is invalid"});
}
var name = request.body.name;
io.sockets.emit("incomingMessage", {message: message, name: name});
response.json(200, {message: "Message received"});
});
io.on("connection", function(socket){
socket.on("newUser", function(data) {
participants.push({id: data.id, name: data.name});
io.sockets.emit("newConnection", {participants: participants});
});
socket.on("nameChange", function(data) {
_.findWhere(participants, {id: socket.id}).name = data.name;
io.sockets.emit("nameChanged", {id: data.id, name: data.name});
});
socket.on("disconnect", function(data) {
participants = _.without(participants,_.findWhere(participants, {id: socket.id}));
io.sockets.emit("userDisconnected", {id: socket.id, sender:"system"});
});
});
http.listen(app.get("port"), app.get("ipaddr"), function() {
console.log("Server ready. IP address: " + app.get("ipaddr") + " ..port:" + app.get("port"));
});
这是客户端代码(index.js)
function init() {
var url = document.domain;
var socket = io.connect(url);
var sId = '';
function updateParticipants(mem) {
$('#participants').html('');
for (var i = 0; i < mem.length; i++) {
$('#participants').append('<span id = ' + mem[i].id + '>' +
mem[i].name + ' ' + (mem[i].id === sId ? '(You)' : '') + '<br> </span>');
}
}
socket.on('connect', function () {
sId = socket.io.engine.id;
console.log('Connected ' + sId);
socket.emit('newUser', {id: sId, name: $('#name').val()});
});
socket.on('newConnection', function (data) {
updateParticipants(data.participants);
$('#messages').prepend('<br> New user joined <hr>');
});
socket.on('userDisconnected', function(data) {
$('#' + data.id).remove();
});
socket.on('nameChanged', function (data) {
$('#' + data.id).html(data.name + ' ' + (data.id === sId ? '(You)' : '') + '<br> ');
});
socket.on('incomingMessage', function (data) {
var message = data.message;
var name = data.name;
$('#messages').prepend('<b>' + name + '</b><br>' + message + '<h6 style = "color: green; font-size: 11px">'+new Date().toString()+'</h6>'+'<hr>');
});
socket.on('error', function (reason) {
console.log('Unable to connect to server', reason);
});
function sendMsg() {
var outgoingMessage = $('#outgoingMessage').val();
var name = $('#name').val();
$.ajax({
url: '/message',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({message: outgoingMessage, name: name})
});
}
function sendAttachment(){
var attachment=$('#attachment').val();
var name = $('#name').val();
$.ajax({
url: '/message',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({message: outgoingMessage, name: name})
});
}
function msgKeyDown(event) {
if (event.which == 13) {
event.preventDefault();
if ($('#outgoingMessage').val().trim().length <= 0) {
return;
}
sendMsg();
$('#outgoingMessage').val('');
var att = $('#attachment').val();
}
}
function msgKeyUp() {
var outgoingMessageValue = $('#outgoingMessage').val();
$('#send').attr('disabled', (outgoingMessageValue.trim()).length > 0 ? false : true);
}
function focusName() {
var name = $('#name').val();
socket.emit('nameChange', {id: sId, name: name});
}
$('#outgoingMessage').on('keydown', msgKeyDown);
$('#outgoingMessage').on('keyup', msgKeyUp);
$('#name').on('focusout', focusName);
$('#send').on('click', sendMsg);
$('#sendFile').on('click',sendAttachment);
}
$(document).on('ready', init);
对于前端,我制作了一个Jade文件(index.jade)
doctype html
html
head
link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Open+Sans')
link(rel='stylesheet', href='/css/style.css')
script(src='//code.jquery.com/jquery-1.11.0.min.js')
script(src='/socket.io/socket.io.js')
script(src='/js/index.js')
title Chatroom
body
h1(style="color: red; text-align: center") Live ChatRoom
div(style="color: red;")
div.inlineBlock
span Your name:
input(type="text", value=" ", style="background-color: blue; color: orange; width: 300px; height:40px; font-size: 35px")#name
br
form#messageForm
textarea(rows="7", cols="60", placeholder="Say something and press enter(maximum 300 characters)",maxlength=300, style ="background-color: black;color: yellow; font-size: 20px")#outgoingMessage
br
input(type="button", value="SEND", disabled=true, style="backround-color: purple; color:black; ")#send
div.inlineBlock.topAligned
b Participants
br
div(style = "color: gold")#participants
div(style = "color: Yellow")#messages
有关如何在代码中进行文件共享的任何建议吗? PS server.js中的'express-fileupload'是我尝试用于文件共享的npm包,但不起作用。
答案 0 :(得分:0)
你是对的:
<input type="file" id="input>
这是一个示例代码,它将发送一个&#34;图像&#34;选择文件后通过WebSockets的事件。处理&#34;图像&#34;的逻辑事件应该类似于你的&#34; incomingMessage&#34;但我建议将它们分开。
document.getElementById("input").addEventListener("change", function (event) {
// Prepeare file reader
var file = event.target.files[0];
var fileReader = new FileReader();
fileReader.onloadend = function (event) {
var image = event.target.result
// Send an image event to the socket
socket.emit("image", image);
};
// Read file
fileReader.readAsDataURL(file);
})
如果要显示来自WebSocket的图像,只需设置&#34; src&#34; image元素的属性:
<img src="" id="output />
侦听WebSocket事件的JavaScript:
socket.on("image", function (image) {
output.src = image;
});
您可以在此处找到通过WebSockets发送图像的完整示例:https://medium.com/@getflourish/from-mobile-to-desktop-cross-device-communication-using-websockets-f9c48f669c8