Check image size before upload image.

The order of checking size and uploading image is wrong. This commit
should fix it.
Close the file after upload the image or exception.