• Hi all. I’m absolutely stumped and can’t seem to find a solution to this.

    Basically, I’m sending a POST request from outside of my wordpress installation ‘/wp-admin/admin-ajax.php‘ to send an image to WordPress and save it as an attachment to one of my posts.

    To do this I have converted the image to a Base64 string on the client side using Javascript, sending that as part of the POST request, decoding that on the server side as part of my script, moving the file to my uploads directory and then attaching the file to a post/adding it to the media library.

    I can do this quite simply using the $_FILES function (a normal upload) but Base64 is required because I need to be able to submit images from all sorts of different applications.

    My code looks like this…

    Step 1 –

    //Collect Base64 and convert to file
        $upload_dir = wp_upload_dir();
        $decoded = base64_decode($_POST['base64File']);
        $filename = 'newImage.jpg';
        $hashed_filename = MD5($filename . microtime()) . '_' . $filename;
        $image_upload = file_put_contents($upload_dir['path'] . '\/' . $hashed_filename, $decoded);
    
        //HANDLE UPLOADED FILE
        if (!function_exists('wp_handle_sideload')) require_once(ABSPATH . 'wp-admin/includes/file.php');
        //upload file to server
        $file_return = wp_handle_sideload($image_upload, array('test_form' => false));
        //return error if there is one
        if(isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
         $jsonReturn = array(
          'error'  =>  'Error uploading.',
          'code' => '95234'
          );
       } else {
       /**
        * See http://codex.wordpress.org/Function_Reference/wp_insert_attachment
        */
       $filename = $file_return['file'];
       $attachment = array(
         'post_mime_type' => $file_return['type'],
         'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
         'post_content' => '',
         'post_status' => 'inherit',
         'guid' => $wp_upload_dir['url'] . '/' . basename($filename)
         );
       $attach_id = wp_insert_attachment( $attachment, $filename, 289 );
       // you must first include the image.php file
       // for the function wp_generate_attachment_metadata() to work
       require_once(ABSPATH . 'wp-admin/includes/image.php');
       $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
       wp_update_attachment_metadata( $attach_id, $attach_data );
       $jsonReturn = array(
          'Status'  =>  'Success'
          );
     }

    Basically what I am struggling to do is get ‘$image_upload‘ to conform to the first required parameter for

    wp_handle_sideload($image_upload, array('test_form' => false));

    as it says there are no file contents when it tries to execute.

    Is there anyone with any idea/experience of dealing with Base64 strings/files???

Viewing 3 replies - 1 through 3 (of 3 total)
  • You could create an actual image on your server first and then use this as attachment. Something along the line of http://stackoverflow.com/questions/15153776/convert-base64-string-to-an-image-file

    Sry, but my browser didn’t show your code until the page reload.

    I think you should create a $_FILE like array instead of using $image_upload when calling wp_handle_sideload()

    $upload_dir       = wp_upload_dir();
    
    // @new
    $upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
    
    $decoded          = base64_decode( $_POST['base64File']) ;
    
    $filename         = 'newImage.png';
    
    $hashed_filename  = md5( $filename . microtime() ) . '_' . $filename;
    
    // @new
    $image_upload     = file_put_contents( $upload_path . $hashed_filename, $decoded );
    
    //HANDLE UPLOADED FILE
    if( !function_exists( 'wp_handle_sideload' ) ) {
    
      require_once( ABSPATH . 'wp-admin/includes/file.php' );
    
    }
    
    // Without that I'm getting a debug error!?
    if( !function_exists( 'wp_get_current_user' ) ) {
    
      require_once( ABSPATH . 'wp-includes/pluggable.php' );
    
    }
    
    // @new
    $file             = array();
    $file['error']    = '';
    $file['tmp_name'] = $upload_path . $hashed_filename;
    $file['name']     = $hashed_filename;
    $file['type']     = 'image/jpg';
    $file['size']     = filesize( $upload_path . $hashed_filename );
    
    // upload file to server
    // @new use $file instead of $image_upload
    $file_return      = wp_handle_sideload( $file, array( 'test_form' => false ) );
    ...
    Thread Starter projectfuturism

    (@projectfuturism)

    Ahh, that is legendary! Thank you so much.

    I figured it had something to do with loading the image onto the server and then conforming $file to the same format array as $_FILES but I couldn’t find that anywhere.

    Thanks heaps, wish I could give you a gold star!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Saving Base64 String as a Media Attachment’ is closed to new replies.