Send image to php file using ajax without using FormData() - php

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 );

Related

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>

Upload video from front end programmatically Wordpress

I am trying to upload video from front end programmatically in wordpress page.
This is my code:
<?php
if (isset($_POST['uploadvideo'])) {
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
}
$uploadedfile = $_FILES['photoContent'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile )
{
$image_url = $movefile["url"];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($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'
);
$listing_post_id = 780 ; // post id
$attach_id = wp_insert_attachment( $attachment, $file, $listing_post_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
/*end file uploader*/
}
}
?>
<form method ="post" action="" name="uploadvideo" enctype="multipart/form-data">
<label for="ug_photo">Your Video Files
<input type="file" value="" name="photoContent" id="ug_photo" class="" multiple="multiple"></label>
<label for="ug_submit_button">
<input type="submit" value="uploadvideo" name="uploadvideo" id="ug_submit_button" class="btn"></label>
</form>
But it is not working. I have hardcoded an post id 780, I will change that later.
Please help. Thanks in advance.
wp_generate_attachment_metadata() won't work if you do not include this file :-
require_once( ABSPATH . 'wp-admin/includes/image.php' );
use wp_upload_bits( $_FILES['picture']['name'], null, #file_get_contents( $_FILES['picture']['tmp_name'] ) ); to upload files other than images
Please try changing the line $uploadedfile = $_FILES['photoContent']; to $uploadedfile = $_FILES['ug_photo']; in your code.

How do I link to external images in my WP posts

I am scraping a site and putting data in my WP site.
There are lots of images in those posts.
I want that when importing that scraped data into my WP site,
I want to link images into my site directly from that external URL instead of downloading image to my server.
I am grammatically importing scraped data to my site.
Here is that part of adding image
// for image
$ins_q = "INSERT INTO wpxw_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, "
. "comment_status, ping_status,"
. "post_password, post_name, to_ping, pinged, post_modified,post_modified_gmt, post_content_filtered,post_parent,"
. "guid,menu_order,post_type,"
. "post_mime_type,comment_count) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$sth = $conn->prepare($ins_q);
if (!$sth->execute(array(
$post_author, $date, $date, "", sanitize_title_with_dashes($image_name), "", "inherit", "open", "closed", '',
str_replace(".", "-", $image_name), '', '', $date, $date, '', $post_id,
"http://photos2.zillowstatic.com/p_f/ISdc6hruhctopo0000000000.jpg"
, 0, "attachment", "image/jpeg", 0
))) {
echo "<h1>Error</h1>";
print_r($sth->errorInfo());
exit();
}
}
MY PROBLEM is that when adding external link to image, images do not show on my post. How can I show images from external resources?
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

$_FILES returns NULL in WordPress file upload function

So I'm still building the settings page for my theme and I'm busy with the file upload function. The wp_handle_upload function is working but the file is not being grabbed.
This is the registered option:
add_settings_field("upload_logo", "Upload Logo", "logo_display", "theme-options", "section");
register_setting("section", "upload_logo", "handle_logo_upload");
This is the function that set's up the theme page:
function theme_settings_page() {
?>
<div class="wrap">
<h1>Theme Panel</h1>
<form method="post" action="options.php" enctype="multipart/form-data">
<?php
settings_fields("section");
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php
}
This is the function that accepts an image:
function logo_display()
{
?>
<form method="post" action="options.php" enctype="multipart/form-data">
<input type="file" name="upload_logo" id="upload_logo" value="<?php echo get_option('upload_logo'); ?>"/>
</form>
<?php
}
This is the function that handles the upload:
function handle_logo_upload() {
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$uploadedfile = $_FILES['upload_logo']['submit'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
echo '<br>';
//return $attach_id;
var_dump($uploadedfile);
//print_r($uploadedfile);
//wp_die('end');
}
return 'fail';
}
When I do I var_dump on the variable $uploadedfile, I get NULL. Why is that?
Here is a screenshot of the settings page for my theme: http://pasteboard.co/yFck7LW.png
This is the empty file that is uploaded when I try to upload something: http://pasteboard.co/yFhrUbB.png
Please help!
Here's the problem:
$uploadedfile = $_FILES['upload_logo']['submit'];
change that to:
$uploadedfile = $_FILES['upload_logo']['name'];

How to differ two uploads in one form with same upload handling?

I have already created a form for my plugin, and it has two upload fields; one for an image and one for a zip-file. They are both using the same upload handler, and I want to save the attachment ID's to the database. The problem is that they use the same upload handler, so the value of the variable with the attachment ID will always be the last upload field. How is the best way to do this? Save in array (first index is first field, second index is second field)? Two upload handler is probably a bit overkill. Any ideas how to solve this in a good way?
This is the function that handles the upload:
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
}
As I said, as both upload fields uses the same function, the $attach_ID variable will be the value of the latest upload.
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
// $ids[]= $attach_id;
// save $attach id here, its correct for this loop, on the next loop it will be different and so on..
}
}
return $ids; // or save here serialize() maybe needed depending on how you are saving.
}

Categories