简体   繁体   English

如何通过Ajax在Wordpress前端上载图像

[英]How to upload image on wordpress front-end via ajax

I working on wordpress plugin for check in(When you click on button check in that open modal window, and you submit your location and comment via ajax, then i save that data to database). 我正在使用wordpress插件进行签入(当您在该打开的模式窗口中单击按钮签入时,您通过ajax提交了位置信息和评论,然后将该数据保存到数据库中)。 Now i need to make on that same modal field to upload file also with ajax.I have tried to send new Form object, but i cant inject action(for wordpress wp_ajax_acion), and i don't receive file on back and. 现在我需要在相同的模态字段上使用ajax上传文件。 Please help me if you have experience with ajax upload image from wordpress front end. 如果您有从wordpress前端上传ajax图像的经验,请帮助我。 i have tried with js: 我试过用js:

`jQuery(document).on('change','#cc_slika', function(e){
var slic = jQuery('#cc_slika').val();
var slicica = jQuery('#upload-image-form');
    var forma =  new FormData(slicica);
    forma.append('slika', slic);
    e.preventDefault();
        jQuery.ajax({
            url: mySecondAjax.ajaxurl,
            type: "POST",

            data:{
              action:'cc_upload_images',
              form: forma,

             },
            contentType: false,
            cache: false,
            processData:false,
            success: function(data)
            {
                alert(data);
            //jQuery("#targetLayer").html(data);
            },
            error: function()
            {
            }
       });
})`

on server side i have done simple print of $_REQUEST array, but i get 0 as response. 在服务器端,我已经完成了$ _REQUEST数组的简单打印,但是我得到0作为响应。 This is code: 这是代码:

    <?php
add_action('wp_ajax_cc_upload_images', 'cc_upload_image');
function cc_upload_image(){
    //$slika = file_get_contents('php://input');
    //$slika1 = serialize($slika);
    //$upload_overrides = array( 'test_form' => false );
    //$premestanje_slike = wp_handle_upload( $slika, $overrides);
   // $slicica = $premestanje_slike['url'];

    //$bla = array('answer' => $slika);
    print_r($_REQUEST);
    exit();
}
?>

i have this working with a wp install: the example below is a multi image upload. 我使用wp安装进行此工作:以下示例为多图像上传。 But to be honest i did away with the ajax due to the time involved with the request. 但老实说,由于涉及到请求的时间,我没有使用Ajax。 It resizes the image before upload. 在上载之前,它将调整图像的大小。

frontend 前端

function resizeBase64Img(base64, width, height) {
  var canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  var context = canvas.getContext("2d");
  var deferred = $.Deferred();

$("<img/>").attr("src", base64).load(function() {
  context.scale(width/this.width,  height/this.height);
  context.drawImage(this, 0, 0); 
  deferred.resolve($("<img/>").attr("src", canvas.toDataURL('image/jpg')));               
});
return deferred.promise();    
}



function readFile(file) {
  var reader = new FileReader();
  var deferred = $.Deferred();

reader.onload = function(event) {
  deferred.resolve(event.target.result);
};

reader.onerror = function() {
  deferred.reject(this);
};

if (/^image/.test(file.type)) {
  reader.readAsDataURL(file);
} else {
  reader.readAsText(file);
}

  return deferred.promise();
}

jQuery(document).on('change', '.imageup', function(event){
  var maximages=4;
  var imagecount=jQuery("#imagesholder > div").length;
  var length= this.files.length;
  var images= new FormData;
  var processKey=0;
  var i=1;
jQuery.each(event.target.files, function(key, value){
  // number of images control. 
  imagecount++;
  if(imagecount > maximages) {
    var full=true;
    jQuery('.imageup').remove();
    jQuery('#imageinput').html("Image Quota Full, Please delete some images if you wish to change them");
    return;   
  } else if (imagecount == maximages) {
    var full=true;
    jQuery('.imageup').remove();
    jQuery('#imageinput').html('<div class="image-box-full">Image Quota Full: delete images to change them</div>');   
   }

//call resize functions
var name=value;
$.when( readFile(value) ).done(function(value) {

    resizeBase64Img(value, 300, 200).done(function(newImg){
         images[processKey]=[];
         images[processKey]['url']=newImg[0].src;
         images[processKey]['name']=name.name;
         processKey++;

  if(length===processKey) {
  //----------------INSERT AJAX TO RUN HERE SUBMITTING IMAGES (THE FORMDATA) E.G
  jQuery.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'POST',
        action: 'uploadimg',
        data: images, 
        cache: false,
        processData: false, 
        contentType: false, 
            success: function(data) {
                console.log(data);
                }
    });
}

 $('#imagesholder').append('<div id="delete'+i+'">'+'<div class="image-box"><div class="box-image"><img src="'+newImg[0].src+'" style="width:50px;"/></div><div class="image-box-text">'+name.name+'</div><input type="image" src="http://testserverdavideec.mx.nf/wp-content/uploads/2014/04/success_close.png" class="deletebutton"  id="delete/i'+i+'"/></div>  </div>');

 i++;

        if(full === true) {
         jQuery('.image-box-full').show();   
        }
    });

  });//end when

  });//end each

 jQuery(this).val('');   
});//end on change

server: 服务器:

function uploadimg() {


$error = false;
//if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
//$upload_overrides = array( 'test_form' => false );
$images=array();

$a=0;
unset ($_POST['action']);

foreach($_POST as $basefile){


    $upload_dir       = wp_upload_dir();
    $upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
    $base64_string = $basefile; 
    echo $basefile;
    $base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string ); 
    $decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
    $source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
    $output_file = $upload_path.'myfilef'.$a.'.jpg'; 
    $images[]=$output_file;
    $a++;       
    $image = fopen( $output_file, 'wb' ); 

    $bytes=fwrite( $image, $source); 
    echo $bytes;
    fclose( $image ); 
}
echo json_encode($images);
exit;

}

add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM