简体   繁体   English

替换原始文件后使用jquery更改图像源

[英]Change image source using jquery after replacing the original file

I came across a very peculiar problem lately... 最近我遇到了一个非常特殊的问题...

I've got the following HTML and javascript 我有以下HTML和javascript

<img id="mycoverpicture" src="users/<?php echo $_SESSION['username'] ?>/cover/cover.jpg" alt="">

I'm using dropzone to upload a JPEG image 我正在使用dropzone上传JPEG图像

$(".cover-picture").dropzone({
  acceptedFiles: "image/jpeg",
      url: 'includes/coveruploader.php',
      maxFiles: 1,
      maxfilesexceeded: function(file) {
      this.removeAllFiles();
      this.addFile(file);
},
success: function(file, response){   
      $('#mycoverpicture').attr('src','users/'+sessionuser+'/cover/cover.jpg');
        }
});

As you can see, as the dropzone finishes uploading the cover picture, the image source changes. 如您所见,当拖放区完成封面照片的上传时,图像源将发生变化。 But the problem here is I have the following scenario. 但是这里的问题是我有以下情况。

Directory: 目录:

users/username/cover/cover.jpeg

When a user uploads a cover picture the cover.jpg is replaced there. 当用户上传封面图片时,cover.jpg会在那里替换。 So when the source of the image is changed dynamically, the old image still exists. 因此,当图像源动态更改时,旧图像仍然存在。

Is it because of the cache? 是因为缓存吗?

Should I clear the cache memory via PHP or JavaScript? 是否应该通过PHP或JavaScript清除缓存?

If I clear the cache memory, there is a problem again. 如果我清除缓存,则再次出现问题。 When the user reloads the page or navigates to another page, all images and fonts would be downloaded again. 当用户重新加载页面或导航到另一个页面时,将重新下载所有图像和字体。 Performance issue will exist... 性能问题将存在...

I need a neat way to achieve the image change with same file name. 我需要一种巧妙的方法来实现使用相同文件名进行图像更改。

How about replace the existing image with a new one? 如何用新图像替换现有图像? That should remove the cache problem. 那应该消除缓存问题。

success: function (file, response) {
     $("#mycoverpicture").replaceWith($("<img/>", {
        src: 'users/' + sessionuser + '/cover/cover.jpg',
        id: mycoverpicture
    }));
}

Try appending some random garbage to the image path, prefixed with a question mark. 尝试在图像路径上附加一些随机垃圾,并以问号为前缀。 When you want to force the image to refresh, change the random garbage. 当您要强制刷新图像时,请更改随机垃圾。

var filename = 'cover.jpg?r=' + Math.random().toString();
$('#mycoverpicture').attr('src','users/'+sessionuser+'/cover/'+filename);

This will defeat caching. 这将使缓存失效。 The browser has no idea what the server is doing with that "query string" and will have to assume that it might be getting a new image, so it'll discard what's in cache. 浏览器不知道服务器使用该“查询字符串”在做什么,并且将不得不假定它可能正在获取新图像,因此它将丢弃缓存中的内容。 The server knows better and will simply ignore it the query string, and serve what it's currently got in that file -- the new image. 服务器知道的更好,将仅忽略查询字符串,并提供该文件中当前所获得的内容-新映像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM