I’m trying to upload a file within own plugin using WP_REST_Request and /wp/v2/media (POST).
I’ve used the code from https://github.com/bobbingwide/wordpress-develop-tests/blob/master/phpunit/tests/rest-api/rest-attachments-controller.php as a reference.
Such coding works OK and the file is uploaded:
$filepath = '/tmp/00001.jpg';
$filename = '00001.jpg';
$request = new WP_REST_Request( 'POST', '/wp/v2/media' );
$request->set_headers(
array(
'Content-Disposition' => "attachment; filename={$filename}",
'Content-Type' => 'image/jpeg',
)
);
$request->set_body( file_get_contents( $filepath ) );
$response = rest_do_request( $request );
but follow coding ends with Http-Error 500 and error message ‘Specified file failed upload test.‘ :
$filepath = '/tmp/00001.jpg';
$filename = '00001.jpg';
$request = new WP_REST_Request( 'POST', '/wp/v2/media' );
$request->set_file_params(
array( 'file' => array(
'file' => file_get_contents( $filepath ),
'name' => $filename,
'size' => filesize( $filepath ),
'tmp_name' => $filepath
) )
);
$request->set_header( 'Content-MD5', md5_file( $filepath ) );
$response = rest_do_request( $request );
Regarding the reference coding such call should also be ok, could you tell me what’s the problem?
Kind regards,
Annie
1