Refactor upload function code