Javascript 节点JS套接字io向客户端聊天应用程序发送图像/文件

Javascript 节点JS套接字io向客户端聊天应用程序发送图像/文件,javascript,ajax,node.js,image,socket.io,Javascript,Ajax,Node.js,Image,Socket.io,我有一个可以工作的聊天应用程序,可以一对一地向用户发送消息。看到它在这里工作: 我现在正在尝试添加一项功能,允许连接的用户从本地机器选择并发送图像 我能够上传我的服务器上使用文件上传Multer的图像 每次客户端选择并上载时,文件都会成功上载到服务器上,但我无法将保存的图像从服务器正确发送/显示到客户端。我想在聊天窗口中同时向发送者和接收者显示图像。有时,它发送但仅发送给第一个连接的用户。并且它会在固定的时间间隔后继续显示相同的图像(看起来上传功能被重复调用) 我的客户端代码HTML代码: &l

我有一个可以工作的聊天应用程序,可以一对一地向用户发送消息。看到它在这里工作:

我现在正在尝试添加一项功能,允许连接的用户从本地机器选择并发送图像

我能够上传我的服务器上使用文件上传Multer的图像

每次客户端选择并上载时,文件都会成功上载到服务器上,但我无法将保存的图像从服务器正确发送/显示到客户端。我想在聊天窗口中同时向发送者和接收者显示图像。有时,它发送但仅发送给第一个连接的用户。并且它会在固定的时间间隔后继续显示相同的图像(看起来上传功能被重复调用)

我的客户端代码HTML代码:

<!--This is where the image should be displayed once uploaded-->

    <img src ="" class="img-rounded img-responsive" id="canvas"></img>

<!-- image upload -->
      <form id        =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/photo"
     method    =  "post"
>
<div class="input-group "> 
   <div tabindex="100" class=" file-caption  kv-fileinput-caption">
   <div class="file-caption-name" title=""></div>
</div>

   <div class="input-group-btn">

       <div tabindex="500" class="btn btn-primary btn-file"><i class="glyphicon glyphicon-folder-open"></i>&nbsp; <span class="hidden-xs">Browse …</span><input id="input-1" type="file" name="userPhoto" class="file"></div>


       <button id="upload-btn" type="submit" name="submit" tabindex="500" title="Upload selected files" class="btn btn-default fileinput-upload fileinput-upload-button"><i class="glyphicon glyphicon-upload"></i> <span class="hidden-xs">Upload</span></button>


   </div>
</div>

</form>

您需要保存图像吗?我可能只是将数据uri发送到clients@vegazz我认为保存已经完成了,所以如果可以保存就好了,但是,如果不能保存就不用担心了,你能告诉我如何直接将数据URI发送到客户端吗?一个基本的代码示例会很有帮助:)thanks@Faizan
var dataURI=“data:image/jpeg;base64,”+imageBufferVar.toString('base64')其中imageBufferVar是一个变量,您在其中存储了从磁盘读取的图像文件。@YiddishNinja谢谢,它可以工作,但每当图像大小超过3 mb时,它就会断开我的socket io聊天。这是非常令人沮丧的,有没有更好的方法使用文件或其他方式来发送图像,而不是使用socket io的base64?您可以设置更高的maxHttpBufferSize(per)。作为DOS防御,它将断开大消息的连接,因此增加连接可以防止断开连接。或者,您可以在单独的操作中发布图像,该操作返回图像的URL,然后传输URL。或者,您可以将数据URI分块发送。是否需要保存图像?我可能只是将数据uri发送到clients@vegazz我认为保存已经完成了,所以如果可以保存就好了,但是,如果不能保存就不用担心了,你能告诉我如何直接将数据URI发送到客户端吗?一个基本的代码示例会很有帮助:)thanks@Faizan
var dataURI=“data:image/jpeg;base64,”+imageBufferVar.toString('base64')其中imageBufferVar是一个变量,您在其中存储了从磁盘读取的图像文件。@YiddishNinja谢谢,它可以工作,但每当图像大小超过3 mb时,它就会断开我的socket io聊天。这是非常令人沮丧的,有没有更好的方法使用文件或其他方式来发送图像,而不是使用socket io的base64?您可以设置更高的maxHttpBufferSize(per)。作为DOS防御,它将断开大消息的连接,因此增加连接可以防止断开连接。或者,您可以在单独的操作中发布图像,该操作返回图像的URL,然后传输URL。或者您可以将数据URI分块并将其分块发送。
$("#upload-btn").click(function(e) {
    var hi = "dd";
    alert("clicked on flash_holder");

    //show to sender itself the image


      //send to server

   socket.emit("uploaded", hi );

});

     socket.on('display uploaded img', function(fileserverpath) {
    /* ... */
        //$('#canvas').empty().append('<img src="/uploads/"'fileserverpath+' height="64px" width="64px">');
 //$('#canvas').attr('src','/uploads/'+fileserverpath);
    var fullpath = '/uploads/'+fileserverpath;

     // addChatMessage('<img src ="/uploads/'+fileserverpath+'" class="img-rounded img-responsive" id="canvas"></img>');

      message = "<img src ='/uploads/"+fileserverpath+"' class='img-rounded img-responsive' id='canvas'></img>";
        addChatMessage({
        username: username,
        message: message
      });

     socket.emit('message', message);

     console.log("cleints receves this from server");

    //$('mssages').prepend($('<img>',{id:'theImg',src: fullpath}))
  });
socket.on("uploaded", function (data) {


      var room = rooms[socket.id];

       console.log("in upload"+data);
 //to save to file
var fs2 = require('fs');

var savedfilename = "";


var d = new Date(); 
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    //callback(null, './uploads');
    callback(null, 'public/uploads');
  },
  filename: function (req, file, callback) {
      var uniquename = uuid.v4();
    callback(null, file.fieldname + '-' + uniquename + '.jpg');
    var actualdate = Date.now()- 1;
    savedfilename = file.fieldname + '-'+ uniquename + '.jpg';




  }

});
var upload = multer({ storage : storage}).single('userPhoto');


app.post('/api/photo',function(req,res){




    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
     //res.end("File is uploaded");
     console.log(savedfilename);

      socket.broadcast.to(room).emit('display uploaded img', savedfilename);




     //socket.emit('display uploaded img', savedfilename);

     savedfilename = " ";

        });

/*   //actually show the image (This is commented out as i am not sure why it does not work
      //Login for sending image working
    // fs2.readFile(__dirname + '/uploads/'+savedfilename, function(err, buf){
     fs2.readFile(__dirname + '/uploads/userPhoto-19.jpg', function(err, buf){
    // it's possible to embed binary data
    // within arbitrarily-complex objects
  socket.emit('image', { image: true, buffer: buf.toString('base64') });
    //console.log(buf);
  }); 



    }); */
});


  });