我正在使用this模块通过socket.io上传图像。
这是客户端代码:
<script src="/swaggerui/swagger-ui-bundle.js"></script>
<script src="/swaggerui/swagger-ui-standalone-preset.js"></script>
<script type="text/javascript">
window.onload = function() {
const ui = window.ui = new SwaggerUIBundle({
服务器端:
<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`);
});
当用户上传图片时,图片可以正常工作,一切都按预期进行,但是当用户再次上传图片时,它将替换服务器中的文件,但不会更新客户端中图片的src。任何建议,将不胜感激。谢谢。
答案 0 :(得分:0)
这是因为每次上载图像时,图像名称都是相同的,并且浏览器无法知道您已上载相同名称的不同图像。虽然有解决方法。您可以像在客户端那样分配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()}`);
});