I recently imitated QQ's album and found that all the pictures in QQ's album were dynamic. Through the packet capture tool, I found that the Http returned status code was 304.
Everyone should know that when the browser caches the file, it will directly read it from the cache, And the status code is 304. so this dynamic cache technology of QQ Album Made me research for a period of time. Now I have recorded the research results and used them for backup.
Implementation principle:
First, you must know the last modification time of the original image.
Second, obtain the Time of the file in the local cache folder.
Finally, for two time comparisons, if the local cache time is later than the last modification time of the original image, the browser will be told that the file already exists locally and no further request is required, set the HTTP status value to 304. Otherwise, you can dynamically generate the small image you need and set the Last-Modified HTTP header to implement local access time.
Well, we know the principle. How can we implement the code?
Code
Protected void Page_Load (object sender, EventArgs e)
{
String imgPath = string. IsNullOrEmpty (Request ["imgPath"])? "": Request ["imgPath"]. ToString ();
Response. ContentType = "image/jpeg ";
DateTime contentModified = System. IO. File. GetLastWriteTime (imgPath );
If (IsClientCached (contentModified ))
{
Response. StatusCode = 304;
Response. SuppressContent = true;
}
Else
{
Thumbnail. GenerateHighThumbnail (imgPath, 80, 80); // the code used to generate the Thumbnail is everywhere on the Internet.
Response. Cache. SetETagFromFileDependencies ();
Response. Cache. SetAllowResponseInBrowserHistory (true );
Response. Cache. SetLastModified (contentModified );
}
}
Private bool IsClientCached (DateTime contentModified)
{
String header = Request. Headers ["If-Modified-Since"];
If (header! = Null)
{
DateTime isModifiedSince;
If (DateTime. TryParse (header, out isModifiedSince ))
{
Return isModifiedSince> = DateTime. Parse (contentModified. ToString ());
}
}
Return false;
}
In the IsClientCached method, return isModifiedSince> = DateTime. Parse (contentModified. ToString ());
Here contentModified is of the DateTime type. Why should it be converted into a string and then converted back to the date type?
I spent a long time here, because the last modification time of the original image is accurate to milliseconds. headers ["If-Modified-Since"]; The request result is a standard London time with no millisecond value. Therefore, If no conversion is performed, a cached image is displayed, the return isModifiedSince> = DateTime. parse (contentModified. toString (); returns false. If this parameter is set to false, the conversion will take effect after milliseconds are removed.