简体   繁体   中英

Display image I just uploaded to the server via ajax

My end goal is to display a canvas element I've uploaded to the server via ajax. I'm able get the image uploaded, but I'm unable to display that same image I've uploaded,

the issue is the image gets saved as name_file.png and that's fine, but I need a way to be able to display that image on the page

this may be an easy question for a WP expert. Thanks

JS code

jQuery("#testbut").click(function(e) {
        e.preventDefault();
        e.stopImmediatePropagation();

var canvas = document.getElementById('bearup');
var dataURL = canvas.toDataURL();
jQuery.ajax({
type: "POST",
url: the_ajax_script.ajaxurl,
data: {
action: 'save_image_canvas',
imgBase64: dataURL,
post_id: '<?php global $post; echo $post->ID; ?>',
}
}).done(function(o) {
console.log('saved');

});
});

add_action( 'wp_ajax_save_image_canvas', 'save_image_canvas' );

function save_image_canvas(){
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);

//saving
$attachment = wp_upload_bits( 'name_file.png', null, $fileData );

$filetype = wp_check_filetype( basename( $attachment['file'] ), null );

$postinfo = array(
'post_mime_type'    => $filetype['type'],
'post_title'    => 'Canvas uploaded image',
'post_content'  => '',
'post_status'   => 'inherit',
);
$filename = $attachment['file'];
$attach_id = wp_insert_attachment( $postinfo, $filename, $postid );

set_post_thumbnail( $_POST["post_id"], $attach_id );
}

Return the uploaded file path as response where you are sending the Ajax request.

<?php 
function save_image_canvas(){
-- Existing code ---


//Return the uploaded file path as ajax response.
if($attach_id){
    $feat_image_url = wp_get_attachment_url(  $attach_id  );
    echo "<img src='$feat_image_url' id='file_upload'>";
    die();
}

}
?>

After success the Ajax request, get the file path as response and display at required place.

jQuery.ajax({
    --- Existing code --
}
}).done(function(data) {
    console.log(data);
    $('.image').html(data);
}

<div class="image"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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