gpt4 book ai didi

javascript - 从 nodejs 以 html 格式共享文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:54 26 4
gpt4 key购买 nike

我正在使用 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 包,但没有用。

最佳答案

你正在看:

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

这是一个示例代码,它将在选择文件后通过 WebSockets 发送“图像”事件。处理“图像”事件的逻辑应该与您的“incomingMessage”类似,但我建议将它们分开。

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;
});

您可以在此处找到通过 WebSockets 发送图像的完整示例:https://medium.com/@getflourish/from-mobile-to-desktop-cross-device-communication-using-websockets-f9c48f669c8

关于javascript - 从 nodejs 以 html 格式共享文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47725311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com