Node JS Socket io将图像/文件发送到客户端聊天应用程序

时间:2016-05-09 09:03:32

标签: javascript ajax node.js image socket.io

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

我现在正尝试添加一项功能,让连接用户从本地计算机中选择和发送图像。

我可以使用Multer Multer ajax file upload上传我的服务器上的图像进行文件上传

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

任何人都可以帮助我吗?

我的客户端代码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>

我的客户端JS代码:

$("#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}))
  });

我的服务器端JS代码:

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



    }); */
});


  });

如果有人可以帮我解决我做错了什么,或者提供代码示例,我将感激不尽?

提前致谢:)

0 个答案:

没有答案