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>
Related
I am working with php,I am getting Base64 image in api,And i want to save/store
into database and want to upload image into server,how can i do this ?
I tried with following code but getting following error
"failed to open content, Http writer doest not support writetable connections"
function imageupload()
{
$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image = base64_decode($files);
$image_name = md5(uniqid(rand(), true));
$filename = $image_name . '.' . 'png';
$path = base_url().'upload/blog/';
file_put_contents($path . $filename, $image);
}
Remove base_url() from path.
OR
Check this out
jQuery :
$(document).on('click', '#upload', function () {
let form_data = new FormData();
let data_url = document.getElementById('my_image').toDataURL('image/png');
data_url = data_url.replace(/^data:image\/(png|jpg|jpeg);base64,/, '');
form_data.append('uploaded_image', data_url);
$.ajax({
url: 'upload-avatar',
method: 'post',
data: form_data,
dataType: 'json',
contentType: false,
async: true,
processData: false,
cache: false
});
});
PHP :
$img = $this->request->getPost('uploaded_image'); // for ci4
$img = $this->input->post('uploaded_image'); // for ci3
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$file_data = base64_decode($img);
file_put_contents(/* my_path and my_file_name */, $file_data);
I am trying to store Canvas image to server through PHP I can see the file but it shows 0 bytes. Can you please help me to fix this issue.
Here is my code below:
HTML:
<img id="image" src="data:image/png;base64,iVBORw0K..." />
JQUERY:
$('.submit').unbind().click(function(){
var dataURL = $('#img').attr('src');
$.ajax({
type: "POST",
url: "saveimage.php",
dataType: 'json',
cache: false,
data: {
imgBase64: dataURL
}
});
});
PHP:
$upload_dir = "../images/";
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
file_put_contents($file, $data);
It should be $img = $_POST['imgBase64']
not $img = $_POST['data'] in your php
as your data object 's key name is imgBase64 when sending the ajax post request
Good evening. I've written a function to programmatically insert a Wordpress post for each of our YouTube videos, using a foreach loop.
Everything is working wonderfully, until I get to inserting the post thumbnail. I am using a function that automatically handles the uploading and inserting of a thumbnail, and associating it with a post (below):
function Generate_Featured_Image($image_url, $post_id) {
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($post_id.'-'.$image_url);
if (wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename;
else $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_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, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
$res1 = wp_update_attachment_metadata( $attach_id, $attach_data );
$res2 = set_post_thumbnail( $post_id, $attach_id );
}
This function does work, but for some odd reason, it only uploads the image from the last video in the loop. For example, if I have 5 videos, 5 posts will be created. Each containing it's own specific information, but the post thumbnail will all be the image from the last (5th) video. None of them have their own thumbnail.
Here's a slimmed down verson of my function that creates the posts:
function createYouTubePost() {
...some other code...
$JSON = file_get_contents('https://www.googleapis.com/youtube/v3/search?order='.$api_order.'&part='.$api_part.'&channelId='.$channel_id.'&maxResults='.$max_results.'&key='.$api_key);
$json_data = json_decode($JSON, true);
foreach ($json_data['items'] as $data) {
$video_id = $data['id']['videoId'];
$video_title = $data['snippet']['title'];
$video_description = $data['snippet']['description'];
$video_thumb_url = $data['snippet']['thumbnails']['high']['url'];
$video_thumb_width = $data['snippet']['thumbnails']['high']['width'];
$video_thumb_height = $data['snippet']['thumbnails']['high']['height'];
$video_publish_date = $data['snippet']['publishedAt'];
$args = array(
'post_title' => substr($video_title, 0, strrpos($video_title, '(')),
'post_content' => $video_description,
'post_status' => 'publish',
'post_type' => 'download',
);
if (!if_download_exists(substr($video_title, 0, strrpos($video_title, '(')))) {
$new_post_id = wp_insert_post($args, true);
if ($new_post_id == 0) {
echo '<br>Could not create the post.';
var_dump($new_post_id);
}
else {
Generate_Featured_Image($video_thumb_url, $new_post_id);
...lots of code to update various post_meta fields...
echo '<br>New post created.<br>';
var_dump($new_post_id);
}
}
}
}
Here you can see the media attachments and how they're all the same:
And here are the individual posts that were created:
As you can see, each image is assigned to it's respective post, but the image is the same.
I have even tried setting the filename of each picture with a unique ID so that they're all different, but that didnt help. I have also confirmed that the image url's that I am passing to the function are all different.
My question is, if I am using my function Generate_Featured_Image() in a foreach loop, and provding it with unique information, why is it only using the last picture in the loop?
Thanks for any help!
I went with another solution. Wordpress' media_sideload_image() function works and is a more straight forward solution for my situation.
Here is the function that I'm now using to assign a thumbnail to a post:
function generateFeaturedImage($image_url, $post_id) {
// required libraries for media_sideload_image
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// $post_id == the post you want the image to be attached to
// $video_thumb_url == the vimeo video's thumb url
// $description == optional description
// load the image
$result = media_sideload_image($image_url, $post_id);
// then find the last image added to the post attachments
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if (sizeof($attachments) > 0) {
// set image as the post thumbnail
set_post_thumbnail($post_id, $attachments[0]->ID);
}
}
Here's the link to the stack exchange solution that I found.
This is my html code for the image field:
<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>
And, I am using jQuery.post() for ajax request.
I am designing a WP plugin in which I want to upload image for the registering user.
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);
}
});
You must put the post id in the wp_insert_attachment function.
$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 );
Hi I am just trying to upload image using navajcrop in yii extension. which upload image using ajax call. I am able to upload image. but problem is that uploaded image can not be view.when i view uploaded image it display below error:- Error interpreting JPEG image file (Not a JPEG file: starts with 0x75 0xab)
controller code:-
public function actionUpload(){
$model = new Register();
if(isset($_POST)){
$rnd = rand(0, 9999);
$img = $_POST['image'];
if($img != '/img/noimage.png' && $img != $model->image){
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = Yii::app()->basePath . '/../themes/front/assets/img/photo/' . $rnd.'.jpg';
file_put_contents($file, $data);
}
}
}
JS code :-
function doSomething(obj,res){ //the 'obj' is IMG tag, 'res' is base64image
$.ajax({
cache: false,
type: 'post',
//url: <?php echo Yii::app()->createUrl('site/upload');?>,
url: baseUrl+"/admin/ajax/Upload",
data: 'image='+res,
success: function(){
obj.attr('src',res);
}
});
}
view code:-
<?php $this->widget('ext.NavaJcrop.ImageJcrop', array(
'config' => array(
'title'=>$model->image,
'image'=>$model->image,//required, all field below are not required.
'id'=>'nava-jcrop',
//'unique'=>true,
'buttons'=>array(
'cancel'=>array(
'name'=>'Cancel',
'class'=>'button-crop',
'style'=>'margin-left: 5px;',
),
/*'edit'=>array(
'name'=>'Edit',
'class'=>'button-crop',
'style'=>'margin-left: 5px;',
),*/
'crop'=>array(
'name'=>'Crop',
'class'=>'button-crop',
'style'=>'margin-left: 5px;',
)
),
'options'=>array(
'imageWidth'=>150,
'imageHeight'=>175,
'resultStyle'=>'position: fixed;top: 400px;max-width:350px;max-height:350px;z-index: 9999;',
'resultMaxWidth'=>350,
'resultMinWidth'=>350,
),
'callBack'=> array(
'success'=>"function(obj,res){doSomething(obj,res);}",
'error'=>"function(){alert('error');}",
)
)
)); ?>
Please help to solve this erro.
Hi I have solved my question it was bug in below syntax.
in controller action :- edit
$img = str_replace('data:image/png;base64,', '', $img);
$file = Yii::app()->basePath . '/../themes/front/assets/img/photo/' . $rnd.'.png';