WP_REST_Attachments_Controller::upload_from_file() WordPress Method

The WP_REST_Attachments_Controller::upload_from_file() method allows you to upload a file from your local computer to your WordPress site. This is useful if you want to transfer a large file that is too big to be transferred using the normal WordPress media uploader.

WP_REST_Attachments_Controller::upload_from_file( array $files, array $headers ) #

Handles an upload via multipart/form-data ($_FILES).


Parameters

$files

(array)(Required)Data from the $_FILES superglobal.

$headers

(array)(Required)HTTP headers from the request.


Top ↑

Return

(array|WP_Error) Data from wp_handle_upload().


Top ↑

Source

File: wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php

	protected function upload_from_file( $files, $headers ) {
		if ( empty( $files ) ) {
			return new WP_Error(
				'rest_upload_no_data',
				__( 'No data supplied.' ),
				array( 'status' => 400 )
			);
		}

		// Verify hash, if given.
		if ( ! empty( $headers['content_md5'] ) ) {
			$content_md5 = array_shift( $headers['content_md5'] );
			$expected    = trim( $content_md5 );
			$actual      = md5_file( $files['file']['tmp_name'] );

			if ( $expected !== $actual ) {
				return new WP_Error(
					'rest_upload_hash_mismatch',
					__( 'Content hash did not match expected.' ),
					array( 'status' => 412 )
				);
			}
		}

		// Pass off to WP to handle the actual upload.
		$overrides = array(
			'test_form' => false,
		);

		// Bypasses is_uploaded_file() when running unit tests.
		if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
			$overrides['action'] = 'wp_handle_mock_upload';
		}

		$size_check = self::check_upload_size( $files['file'] );
		if ( is_wp_error( $size_check ) ) {
			return $size_check;
		}

		// Include filesystem functions to get access to wp_handle_upload().
		require_once ABSPATH . 'wp-admin/includes/file.php';

		$file = wp_handle_upload( $files['file'], $overrides );

		if ( isset( $file['error'] ) ) {
			return new WP_Error(
				'rest_upload_unknown_error',
				$file['error'],
				array( 'status' => 500 )
			);
		}

		return $file;
	}


Top ↑

Changelog

Changelog
VersionDescription
4.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.