you can do this using the media_handle_upload() function. This is a working example that you can use as a guide for your requirements:
First Create your HTML form
<form method="post" id="uploadCartaAnno" enctype="multipart/form-data">
<input class="text-input" name="carta_ano" type="file" id="carta_ano" multiple="false"/>
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input name="updatecarta_ano" type="submit" id="updatecarta_ano" class="hp-btn-file -icon-upload" value="Subir formato" />
<input name="action" type="hidden" id="action" value="update-user" />
</form>
Then your PHP code
if (
isset( $_POST['my_image_upload_nonce'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
) {
// The nonce is valid and it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
$attachment_id = media_handle_upload( 'carta_ano', $comId );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// Show some error message if nonce fails.
}