Try it.
Save the image to disk in the workspace. The best thing is to keep the workspace at the same level as the final destination. It is also best to place it in a separate directory.
Start the transaction with the database.
Insert your user.
Rename the image file after the user ID.
Commit transaction.
What does this mean, he first performs the most risky operation, saving the image. All sorts of things can happen here: the system may fail, the disk may fill up, the connection may close. This is (most likely) the most time-consuming of your operations, so it is definitely the most risky.
Once this is done, you will begin the transaction and insert the user.
If the system does not work at this time, your insert will be rolled back, and the image will be in the temporary directory. But for your real system, "nothing happened" effectively. The temporary directory can be cleared using an automated function (i.e., Clear upon reboot, clear everything in X hours / days, etc.). Files must have a very short amount of time in this directory.
Then rename the image to its last place. File renames are atomic. They work, or they do not.
If the system is after this, the user line will be rolled back, but the file will be at the final destination. However, if after a reboot someone tries to add a new user who has the same user ID as the one that failed, their downloaded image will simply overwrite the existing one - do no harm, not a foul. If the user ID cannot be reused, you will have a lost image. But it can reasonably be cleaned once a week or once a month through an automatic procedure.
Finally, complete the transaction.
At this point, everything is in the right place.
source share