1

I need to save and edit entities via services like {user, nodes, products ...etc}

the problem comes with images posted form mobile apps encoded base64.

I saved the file and stored the object in session to be used in hook_services_request_postprocess_alter to be added to the entity saved by loading it again and assign the value to the field

// in preprocess
$_SESSION['file'] = file_save_data(base64_decode($args[0]['image']),'public://test.png');

// in postprocess
$product = entity_load('commerce_product', array($result->product_id));
$wrapper = entity_metadata_wrapper('commerce_product', $product);

//$wrapper->field_field_user_avatar->file->set($_SESSION['file']);
//$wrapper->field_field_user_avatar['und'][0]['value']=(array)$_SESSION['file']; 
//$wrapper->save();   
entity_save('commerce_product', $product);

what missing here I have tried many answers either adding the file object to the field when creating the field nor entity saving

2
  • 1
    First use Services to create the file and retreive its ID, then try using fid instead of value and set it equal to the file id. Commented Mar 4, 2015 at 9:33
  • The field is not file reference field its image upload field Commented Mar 5, 2015 at 12:49

1 Answer 1

3

It works after getting file mime type here is the code sample

$data = base64_decode($args[1]['avatar']);    
$finfo = finfo_open();
        $mime_type = finfo_buffer($finfo, $data, FILEINFO_MIME_TYPE);
        finfo_close($finfo);
        // get file type png. jpg
        $ext = $mime_type ? str_replace('image/', '', $mime_type) : 'png';
        $file_name = str_replace(' ', '-', $args[1]['name']);

then you we save the file using

$file = file_save_data($data, 'public://users/'.$file_name.'.'.$ext, FILE_EXISTS_REPLACE);

    $args[1]['field_field_user_picture'] = array(
        'fid' => $file->fid,
        'width' => 100,
        'height' => 100,
        'alt' => $args[1]['name'],
        'title' => $args[1]['name']
    );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.