3

This is my html code for the image field:

<div class="row input_detail">
    <div class="col-lg-4 col-md-4 ">
        <label>Upload Image:</label>
    </div>
    <div class="col-lg-8 col-md-8">
        <input type="file" id="picture" name="pro_picture"/>
    </div>
</div>

And, I am using jQuery.post() for ajax request. I am designing a WP plugin in which I want to upload image for the registering user.

Annapurna
  • 529
  • 1
  • 6
  • 19
  • use hidden iframes if you don't want to use FormData() – madalinivascu Aug 01 '16 at 08:07
  • For what reason do you not want to use FormData? It is pretty much the only way of making an AJAX request that sends binary data. Your alternative is a hidden frame or standard POST request. – Rory McCrossan Aug 01 '16 at 08:09
  • i am not using form tag in my wp page, submitting the details on 'click' action of submit button. i want to add the image upload functionality. – Annapurna Aug 01 '16 at 08:13
  • 1
    @Annapurna [this](http://stackoverflow.com/a/26690647/861704) answer should solve your problem. You can use `FormData` without using form too. – Jigar Aug 01 '16 at 08:17

1 Answers1

0
var image="";
$("#picture").on('change',function(){
    if (this.files && this.files[0]) {
        var FR= new FileReader();
        FR.onload = function(e) {       
            image=e.target.result;
        }
        FR.readAsDataURL( this.files[0] );
    }
});
$.ajax({
    url: '<?php echo $this->getUrl("*/*/upload/id/" . $this->getRequest()->getParam('id')) ?>', // change it to your image handle controller
    type: 'POST',
    data: {"image":image},
    cache: false,
    processData: false,
    contentType: false, 
    success: function(data, status, xhr) {                             
          //do your stuff              
    },
    error: function(xhr, status, error) {                    
        console.log('Error saving the images to database: ' + status);                    
    }
}); 

You must put the post id in the wp_insert_attachment function.

    $upload_dir = wp_upload_dir();  
    $filename   = 'sample.jpg';             
    if( wp_mkdir_p( $upload_dir['path'] ) ) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }                       
    $base64img = str_replace('data:image/jpeg;base64,', '', $_POST['image']);
    $img_data = base64_decode($base64img);  
    $validate_image = imagecreatefromstring($img_data);
    if($validate_image  !== false){     
        imagedestroy($validate_image);      
        file_put_contents($file, $img_data);
        $wp_filetype = wp_check_filetype( $filename, null );            
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title'     => sanitize_file_name( $filename ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );      
        $attach_id = wp_insert_attachment( $attachment, $file,  'put the post id here');            
        require_once(ABSPATH . 'wp-admin/includes/image.php');          
        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );            
        wp_update_attachment_metadata( $attach_id, $attach_data );
Ashok Kumar
  • 143
  • 11