我的最终目标是显示我已通过ajax上传到服务器的画布元素。我可以上传图片,但是无法显示我上传的图片,
问题是图像被保存为name_file.png,这很好,但是我需要一种能够在页面上显示该图像的方法
对于WP专家来说,这可能是一个简单的问题。谢谢
JS代码
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 );
}
答案 0 :(得分:0)
将上传的文件路径作为响应发送到您发送Ajax请求的位置。
<?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();
}
}
?>
Ajax请求成功后,获取文件路径作为响应并显示在所需位置。
jQuery.ajax({
--- Existing code --
}
}).done(function(data) {
console.log(data);
$('.image').html(data);
}
<div class="image"></div>