diff --git a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php
index 90ab5185fd..b283d9fab5 100644
--- a/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php
+++ b/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php
@@ -106,18 +106,18 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
 
 		if ( ! empty( $files ) ) {
 			$file = $this->upload_from_file( $files, $headers );
+			$name = $files['file']['name'];
+			$ext  = pathinfo( $name, PATHINFO_EXTENSION );
+			$name = wp_basename( $name, ".$ext" );
 		} else {
 			$file = $this->upload_from_data( $request->get_body(), $headers );
+			$name = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
 		}
 
 		if ( is_wp_error( $file ) ) {
 			return $file;
 		}
 
-		$name       = basename( $file['file'] );
-		$name_parts = pathinfo( $name );
-		$name       = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) );
-
 		$url  = $file['url'];
 		$type = $file['type'];
 		$file = $file['file'];
@@ -140,7 +140,7 @@ class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
 		$attachment->guid           = $url;
 
 		if ( empty( $attachment->post_title ) ) {
-			$attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
+			$attachment->post_title = sanitize_text_field( $name );
 		}
 
 		// $post_parent is inherited from $attachment['post_parent'].
