Refactor upload_file function