2016-08-01 11 views
3

これは、画像フィールドのための私のhtmlコードです:はいるFormDataを使用せずに、AJAXを使用してPHPファイルに画像を送る()

<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> 

そして、私はAjaxのリクエストのためのjQuery.post()を使用しています。 登録しているユーザーの画像をアップロードしたいWPプラグインを設計しています。

+0

FormData()を使用したくない場合は非表示のiframeを使用 – madalinivascu

+0

FormDataを使用しない理由は何ですか?バイナリデータを送信するAJAXリクエストを作成する唯一の方法です。あなたの選択肢は隠しフレームまたは標準のPOSTリクエストです。 –

+0

私はwpページでフォームタグを使用せず、送信ボタンの「クリック」アクションに関する詳細を提出しています。私は画像のアップロード機能を追加したい。 – Annapurna

答えて

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);      
    } 
}); 

投稿IDをwp_insert_attachment関数に入れる必要があります。

$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); 
関連する問題