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;
        }
      }

Published by

Unknown's avatar

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a comment