当用户再次上传图片时,图片的 src 没有改变 (socket.io)

src of image doesn't change when user uploads image again (socket.io)

我正在使用 this 模块通过 socket.io 上传图片。
这是客户端代码:

<img src="/img/avatar-2-128.png" alt="" id="signinbox_photo"> //avatar-2-128.png is an avatar that will be replaced
<input type="file" id="siofu_input" />


//upload the image to the server
var uploader = new SocketIOFileUpload(socket);
uploader.listenOnInput(document.getElementById("siofu_input"));

socket.on('update photo', function(data){ //update the src attr of the img tag
    var signinbox_photo = $('#signinbox_photo');
    signinbox_photo.attr("src",`/img/user_images/${data.id}.jpg`);
});

服务器端:

var fs = require('fs');
var siofu = require("socketio-file-upload");

io.sockets.on('connection', function(socket) {
    var uploader = new siofu();
    var dir = "./public/img/user_images/"
    uploader.dir = dir;
    uploader.listen(socket); //save the file

    uploader.on("saved", function(event){
        fs.rename(dir + event.file.name, dir + socket.id + ".jpg", function(err) { //replace the file name to socket id
            if ( err ) console.log('ERROR: ' + err);
        });
        io.sockets.emit('update photo', {id: socket.id}) //emit to client so it updates the src of the image
    });

});

当用户上传图片时,一切正常,但当用户再次上传时,它替换了服务器中的文件,但没有更新客户端中图片的src。任何建议将不胜感激。谢谢。

这是因为每次上传图片,图片名称都是一样的,浏览器不可能不知道你上传了同名的不同图片。虽然有解决方法。您可以在客户端分配 src 时添加随机数作为查询参数,如下所示:

//upload the image to the server
var uploader = new SocketIOFileUpload(socket);
uploader.listenOnInput(document.getElementById("siofu_input"));

socket.on('update photo', function(data){ //update the src attr of the img tag
    var signinbox_photo = $('#signinbox_photo');
    signinbox_photo.attr("src",`/img/user_images/${data.id}.jpg?r=${Math.random()}`);
});