https://codex.wordpress.org/Function_Reference/media_handle_upload
Maybe this can help you out. This function handles the upload of the file and adds the attachment as WordPress media record. Don’t forget to include dependencies if you’re uploading from frontend.