I tried two methods for uploading blob files to WordPress media library.
In first method i tried move blob tmp file to WordPress upload directory with move_uploaded_file(). Then tried upload this temp file with media_handle_sideload() function.
It is blob file that i sent via ajax:
array(
'name' => '2021-03-26_02-58-09',
'type' => 'image/png',
'tmp_name' => 'C:\Users\me\AppData\Local\Temp\php28D8.tmp',
'error' => 0,
'size' => 1880058,
);
Ajax process:
$file = $_FILES['file'];
$upload_dir = wp_upload_dir();
move_uploaded_file( $file['tmp_name'], $upload_dir['path'] . '/' . $file['name'] );
$url = $upload_dir['url'] . '/' . $file['name'];
$tmp = download_url( $url );
$file_array = array(
'name' => basename( $url ),
'tmp_name' => $tmp,
);
$id = media_handle_sideload( $file_array, 0 );
var_dump( $id );
But it returns Sorry, this file type is not permitted for security reasons
error.
So i tried this with wp_insert_attachment() function. It is uploading file but without image extension (.jpg, .png) and it is not generating additional image sizes. Here is what i tried:
$file = $_FILES['file'];
$upload_dir = wp_upload_dir();
move_uploaded_file( $file['tmp_name'], $upload_dir['path'] . '/' . $file['name'] );
$id = wp_insert_attachment(
array(
'guid' => $upload_dir['path'] . '/' . $file['name'],
'post_mime_type' => $file['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $file['name'] ),
'post_content' => '',
'post_status' => 'inherit',
),
$upload_dir['path'] . '/' . $file['name']
);
var_dump( $id );