2016-08-01 2 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> 

그리고, 내가 아약스 요청에 대한 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);      
    } 
}); 

wp_insert_attachment 함수에 게시물 ID를 넣어야합니다.

$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); 
관련 문제