Don't store metadata if storing the file fails.

I didn't give enough thought to the original decision to store metadata even if storing the file fails.  In retrospect it doesn't make a ton of sense.  This patch fixes it, so metadata is not stored if storing the file fails.  The patch also includes some refactoring to make the final fix a bit cleaner.