Work-Around Browser Cache when it comes to Profile Images

If you allow users to change their profile pictures or if there are images which are frequently updated by users and those images use a standard name you can work-around browser caching by adding a version number to the image name when it is saved to the disk and stored in a database.

      //Set the image path.
      if (fileUpload.HasFile)
      {
        try
        {
          string imageFilePath = PortalSettings.HomeDirectoryMapPath;
          string imageName = USER_IMAGE + "." + 0 + ".jpg";
          if (!string.IsNullOrEmpty(location.UserImagePath))
          {
            //Find out what version the current file is at
            string[] parts = location.UserImagePath.Split('.');
            if (parts.Length == 3)
            {
              int version = int.Parse(parts[1]);
              int nextVersion = version + 1;
              imageName = USER_IMAGE + "." + nextVersion + ".jpg";

              string oldImagePath = imageFilePath + location.UserImagePath.Remove(0, 1);
              if (System.IO.File.Exists(oldImagePath))
                System.IO.File.Delete(oldImagePath);
            }
          }

          fileUpload.SaveAs(imageFilePath + imageName);
          location.UserImagePath = "/" + imageName;
          imgUserImage.ImageUrl = "/" + imageName;
          imgUserImage.Visible = true;
          AddImageToCache(imageFilePath + imageName);
        }
        catch (Exception ex)
        {
          if (ExceptionHandler.ProcessException(ex, ExceptionPolicy.General, ModuleConfiguration))
            throw;
        }
      }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s