0

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 );
wpuzman
  • 340
  • 1
  • 5
  • 14
  • You can convert blob file to image and the upload see here [Php : Convert a blob into an image file](https://stackoverflow.com/questions/6106470/php-convert-a-blob-into-an-image-file) – Bhautik Mar 26 '21 at 11:59
  • Can you suggest any WordPress way? Because it is for my WordPress plugin and it will be used by thousand users. So GD, iMagick or other extensions may not have been installed on users' server. – wpuzman Mar 26 '21 at 12:13

0 Answers0