从nodejs的HTML文件共享

我正在使用nodejs制作Chatroom。 我正在使用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 

任何build议如何在代码中做文件共享? PS server.js中的“express-fileupload”是一个npm包,我尝试使用文件共享,这是行不通的。

你正在看:

 <input type="file" id="input> 

这里是一个示例代码,它将在文件被选中后通过WebSockets发送一个“图片”事件。 处理“图像”事件的逻辑应该类似于你的“incomingMessage”,但我build议将它们分开。

 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的图像,只需在图像元素上设置“src”属性即可:

 <img src="" id="output /> 

以及侦听WebSocket事件的JavaScript:

 socket.on("image", function (image) { output.src = image; }); 

您可以在这里find一个通过WebSockets发送图像的完整示例: https : //medium.com/@getflourish/from-mobile-to-desktop-cross-device-communication-using-websockets-f9c48f669c8