B4J Code Snippet [Server] Disable/Enable cache for specific static files

1. Create a Server Filter class module (eg. CacheFilter) and add this code in its Filter sub :
B4X:
' Test if the request is for a static file, only static files will be cached.
' File.Combine(File.DirApp, "www") is just for example purposes. Replace this with your StaticFilesFolder (StaticFilesFolder property from your server object)
If File.Exists(File.Combine(File.DirApp, "www"), req.RequestURI) Then
  ' if the request was made for myfile.ext then we set response header to disable caching for this file
  If File.GetName(req.RequestURI) = "myfile.ext" Then
    resp.SetHeader("Cache-Control", "no-cache, no-store") ' disables cache for HTTP 1.1
    resp.SetHeader("Pragma", "no-cache") ' disables cache for HTTP 1.0
    resp.SetHeader("Expires", "0") ' disables cache for Proxies
    Return True ' exit the sub and allow the request to proceed
  End If
  ' we set the response header to cache the requested resource for 7 days - max-age is in seconds
  resp.SetHeader("Cache-Control", "public, max-age=604800")
End If
Return True
2. Call the AddFilter method of your server object:
B4X:
' the Filter sub from the CacheFilter class will fire at every request
srvr.AddFilter("/*", "CacheFilter", False)
3. If you call the SetStaticFilesOptions method of your server object do NOT add the cacheControl options to it - that will override the code from above.
 
Last edited:
Top