A common problem when you implement file uploads is to set a proper name for the files in order to avoid name collisions. Drupal have a good technique to avoid name collisions, basically this is what Drupal does.
- uploading img.jpg the name will be img.jpg
- uploading img.jpg again, Drupal will be renamed to img_0.jpg , since img.jpg is already taken
- uploading img.jpg one more time, Drupal will use the name img_1.jpg.
- if we delete img_1.jpg the file name will be free.
- if we upload another img.jpg after that, Drupal will select img_1.jpg as name.
The problem that comes with this is if the first img_1.jpg was already served, the file were already cached in the frontend cache (varnish, squid, any other) or even in the client browser. If when you upload a new file with the same name of the old deleted file it might render in the client browser a wrong image.
The issue occurs when last file gets deleted and then a different file with the original name is uploaded.
For us, and the reason we spot this issue, is that img_1.jpg was already served and since we use Varnish as frontend cache, varnish already have the original img_1.jpg file in his storage, so it will serve an old img_1.jpg file, not the new one. Keep in mind that this can happen with any frontend cache or CDN.
To avoid this kind of issues we implemented the File (Field) Paths module.
This module lets you change the file name and the destination path by using entity based tokens. It’s very customizable
Once you enable it you can Edit the File path or the File name by focusing the cursor in one input and then clicking the ‘Browse available tokens’ link. A modal window shall open showing the different kind of available tokens to use.
You have to click the tokens you want to implement for the path or file name, also you can concat characters between each token by typing it in the input. Eg: I used the original file name and I concatenated with a dot (.) the original file extension.
Save the changes and from now, every time you upload an image this module will rename it with those tokens.
Thats all guys, keep hacking!