有没有办法一个ajax文件上传jQuery中之后刷新的图像?没有办法、文件上传、图像、ajax

2023-09-10 13:48:24 作者:暮色倦

我在页面上的图像。我使用了AJAX表格插件上传单个图像,照片上传后,我想刷新已经是页面上的图像。

I have an image on the page. I'm using the AJAX form plugin to upload a single image, and after the photo has uploaded I'd like to refresh the image that is already on the page.

$("#profilePicForm").ajaxForm(function() { 
    alert("Photo updated");
    $("#newPhotoForm").slideToggle();
    $("#profilePic img").load(function() {
        $(this).hide();
        $(this).fadeIn('slow');
    }).attr('src', '/Content/UsrImg/Profiles/PhotoName.jpg');
}); 

新上传的文件具有相同的名称作为旧的,所有需要的是一种方式来刷新图像。既然是同一个名字,缓存的方式获得 - 在这篇文章中描述的没有工作的方法

任何想法?

推荐答案

您挂的文章不是在这里工作,但你可以打破一个查询字符串缓存中的图像上,像这样的:

The article you linked isn't working here, but you can break the cache with a query string on the image, like this:

$("#profilePicForm").ajaxForm(function() { 
  alert("Photo updated");
  $("#newPhotoForm").slideToggle();
  $("#profilePic img").load(function() {
    $(this).hide();
    $(this).fadeIn('slow');
  }).attr('src', '/Content/UsrImg/Profiles/PhotoName.jpg?' + new Date().getTime());
}); 

此强制浏览器检查该图像再次,由于时间戳被添加到查询字符串,它每次都不同了。这意味着浏览器就不能信任缓存了,因为这是一个稍微不同的服务器的请求......所以它会导致重新取像你想要的。

This forces the browser to check for the image again, since the timestamp is being adding to the query string, it's different every time. This means the browser just can't trust the cache anymore, since that's a slightly different server request...so it'll result in a re-fetch like you want.