如何在本地主机上设置正确的路径

时间:2019-03-31 22:32:50

标签: image socket.io localhost

嗨,

我在页面上显示图片时遇到问题。 我不知道如何设置显示图片的正确路径。 我使用socket.io并表达。该页面正在 Localhost 服务器

上运行

这是我显示图片的代码,但是它不起作用。

img src =“ uploads / images.png”

在服务器端,我做了这个“ app.use(express.static('public'));”公开。但这不起作用,有人可以帮助我吗? 正确的道路是什么?

我的文件夹结构是这个

Folder structure

1 个答案:

答案 0 :(得分:0)

服务器端:

var app = require('express')();
var express = require('express'); 
var upload = require('express-fileupload');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var multer = require('multer');
var fs = require('fs');
app.use(upload());
app.use(express.static('public'));


var users = {};
var allUsers = [];



function actualTime(){
var d = new Date();
return d.toLocaleTimeString();}


http.listen(3000, function(){
  console.log('listening on *:3000');
});

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});






io.on('connection', function(socket){



    app.post('/upload',function(req,res){
          console.log(req.files);
          if(req.files.upfile){
            var file = req.files.upfile,
              name = file.name,
              type = file.mimetype;
            var uploadpath = __dirname + '/uploads/' + name;
            file.mv(uploadpath,function(err){
              if(err){
                console.log("File Upload Failed",name,err);
                res.send("Error Occured!")
              }
              else {
                console.log("File Uploaded",name);
                console.log("guckmal");
                io.emit('file', name);
                res.send('sasa');
              }
            });
          }
          else {
            res.send("No File selected !");
            res.end();
          };
        })



      socket.on('username', function(data,callback){
            if(data in users || data.length<=2){
                callback(false);
            }else{

                callback(true);
                socket.nickname = data;
                users[socket.nickname] = socket;
                // to get a message for all users who are not in the priavte chat
                allUsers.push(""+socket.nickname);
                for(var test=0; test<allUsers.length;test++){
                    console.log(allUsers[test]);
                users[allUsers[test]].emit('usernames', {list:Object.keys(users), nick: allUsers[test]});
            }
                io.emit('chat message',{msg:"joined the Chatroom", nick:socket.nickname,  time:actualTime()});
            }
        });

      socket.on('chat message', function(data, callback){
            console.log(socket.nickname);
            console.log('User: ' + socket.nickname + ' message: ' + data);
            var msg = data.trim();
            if(msg.substr(0,3)=== '/w '){
                console.log("private chat");
                msg= msg.substr(3);
                var temp = msg.indexOf(' ');
                if(temp !== -1){
                    console.log("private chat stap 2");
                    var name = msg.substring(0,temp);
                    var msg = msg.substring(temp+1);
                    if(name in users){
                        console.log("private chat stap 3");
                        users[name].emit('private chat', {msg:msg, nick:socket.nickname, time:actualTime()});
                        for(var i=0; i<allUsers.length;i++){
                            if((name !==allUsers[i])){
                                if(allUsers[i] !== socket.nickname){
                                users[allUsers[i]].emit('private chat',{msg:"private message was send from "+socket.nickname+" to "+name, nick:socket.nickname,  time:actualTime()});
                            }else{
                                users[socket.nickname].emit('private chat',{msg:"you send a private messgae to "+name, nick:"chat", time:actualTime()});
                            }
                            }
                        }
                    }else{
                        callback(' user name doesnt exist');
                    }

                }else{
                    callback('Error! Please enter a message');
                }
            }else{
            io.emit('chat message', {msg:msg, nick:socket.nickname, time:actualTime()});
            }

          });

      socket.on('disconnect', function(data){
            delete users[socket.nickname];
          io.emit('chat message',{msg:"leaved the Chatroom", nick:socket.nickname,  time:actualTime()});
          io.sockets.emit('usernames', {list:Object.keys(users)});
      });

    });

客户端

$(function () {
var socket = io();





$('#loginForm').submit(function(e){
  e.preventDefault(); // prevents page reloading
  socket.emit('username', $('#u').val(), function(data,callback){
      if(data){
          $('#nickWrap').hide();
          $('#contentWrap').show();

    }else if(($('#u').val()).length<=2){
    document.getElementById("u").value="";
    document.getElementById("u").placeholder ="Sorry but Username length is less then three :(";
  }else{
        document.getElementById("u").value="";
        document.getElementById("u").placeholder ="Sorry but Username already taken :(";
    }

  });

  });

$('#chatForm').submit(function(e){
    e.preventDefault(); // prevents page reloading
    if(privateUsers.length>0){
        for(var i=0;i<privateUsers.length;i++){
            socket.emit('chat message','/w '+ privateUsers[i] +' '+ $('#m').val(),    function(data){
                // add stuff later
                 $('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
              });
        }
    }else{
        socket.emit('chat message', $('#m').val(), function(data){
            // add stuff later
             $('#messages').append($('<li>').text(data.time + " " + data.nick+': '+ data.msg ));
          });
    }

    $('#m').val('');
    return false;
  });
  socket.on('chat message', function(data){
       $('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
  });

  socket.on('file', function(data){
   var img = document.getElementById('bild');
   images.push[data];
   var name = data;
   console.log(name);
$('#messages').append('<li><img src="uploads/images.png" />'+ '</li>');


   img.setAttribute('src','data:image/jpeg;base64,' + window.btoa(images));

 });




  socket.on('private chat', function(data){
    $('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
  });


  socket.on('usernames', function(socket, data){
    console.log("2222222222");


// to get a massage for all users who are not in the priavte chat

console.log(socket.nick);
socketName = socket.nick;


});


  socket.on('usernames', function(data){
      document.getElementById("userList").innerHTML = "";
    var temp;
    var indexTemp;
    var me= "";
    var sortData = [];
      for(var i=0;i<data.list.length;i++){
      if(data.nick === data.list[i]){

        indexTemp = i;
        /*   temp = data.list[i];
           indexTemp =i;
          data.list[i]= "Ich";*/
          me ="My Name: ";
        }
    }
        // sort list

        sortData.push(data.list[indexTemp]);
        for(var l=0; l<data.list.length;l++){
         if(indexTemp !=l){
          sortData.push(data.list[l]);
        }
        }

      for(var i =0; i<sortData.length;i++){
      if(i==0){
          $('#userList').append('<li style="list-style:none "><buttonid="'+sortData[i]+'" onclick='+'"addUsers()"'+
                                     ' style="width: 100%; background: rgb(130, 224, 255); border: none; padding:10%; margin-bottom:2%; "'+'>'+"My Name: "+ sortData[i]
                                    +'</button></li>');
                    //data.list[i]= temp;

    }else{
      $('#userList').append('<li style="list-style:none "><button id="'+sortData[i]+'" onclick='+'"addUsers(\''+sortData[i]+'\')"'+
                                     ' style="width: 100%; background: rgb(130, 224, 255); border: none; padding:10%; margin-bottom:2%; "'+'>'+ sortData[i]
                                    +'</button></li>');
    }
  }
      // }


  });

  });



function addUsers(name){
    if(privateUsers.length==0){
        console.log("erstes objekt");
        document.getElementById(name).style.background = "rgb(1, 254, 185)";
        privateUsers.push(name);

    }else{

    for(var i=0;i<privateUsers.length;i++){
        if(name==privateUsers[i]){
            console.log("gel�scht");
            document.getElementById(name).style.background = "rgb(130, 224, 255)";
            privateUsers.splice(i,1);
            return;
        }
    }
    console.log("drinnen");
    document.getElementById(name).style.background = "rgb(1, 254, 185)";
    privateUsers.push(name);



    }
}