I'm setting up a PWA with Angular 7. Here is my problem: If a User is logged in the Application, he can Upload a profile picture. The picture will be uploaded in the /assets folder, which is cached by the service worker.
As I understand the service worker, the application itself recognizes updates by the filenames in the project main folder. If the filenames changes, the service worker gets the new version.
Maybe you see the problem now: If a User uploads a picture, no filename will change because it is no update from the Angular project. So the User see his "old" profile picture for a long time OR if he refreshes the browser cache.
I tried to upload the profile pictures with php in the angular assets folder. Is this the correct way?
This code works very well for me, but I'm not sure if this is the correct way to save pictures with a PWA. I want the service worker cache for my pictures, but if a User uploads a picture I want an instant refresh.
$path = '../assets/img/profile_pictures/';
if (isset($_FILES['file'])) {
$originalName = $_FILES['file']['name'];
$ext = '.' . pathinfo($originalName, PATHINFO_EXTENSION);
$generatedName = $_POST['id'];
$filePath = $path . $generatedName . '.png';
if (!is_writable($path)) {
echo json_encode(array(
'status' => false,
'msg' => 'Destination directory not writable.'
));
exit;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
echo json_encode(array(
'status' => true,
'originalName' => $originalName,
'generatedName' => $generatedName
));
}
} else {
echo json_encode(
array('status' => false, 'msg' => 'No file uploaded.')
);
exit;
}
It sounds like what you're trying to achieve is allowing a user to update their profile picture. This shouldn't be stored anywhere in your Angular frontend - it should be stored in a backend database somewhere, and then you make a request to load that picture when a user goes to the containing page.
This way, every time they go to the page, they make a new request for data. Unless they have no internet connection; in which case the service worker will return you its latest cached image (if you have set the query URL to be cached in your ngsw-conf.json).
If you don't want to make your own backend service to do this; you can use a service such as Firebase, which has several libraries for communication with Angular. You can check this out with code samples here: https://firebase.google.com/docs/storage/web/upload-files