Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Upload HTML5 Canvas to Wordpress using ajax WordPress

  • SOLVED

I have a canvas on a front end of a WordPress site just a regular canvas tag nothing special and I'm trying to take the output and upload to WordPress eg:


canvas = document.getElementById("doc"),
data = canvas.toDataURL();


I would like to be able to upload this to the media library the issue is the size of the image is a bit large. 1-2mb so it always fails when uploading. I have tried a few methods online and have not been able to get them working. This could be jquery or just javascript. Then if I need to handle the file s $_FILES or another method.

Answers (4)

2019-06-08

John Cotton answers:

$.ajax({
type: "POST",
url: ****admin-ajax-url*****,
data: {
action: 'canvasUpload'
uploadImage: dataURL
}
}).done(function(o) {
});


****admin-ajax-url***** needs replacing with a var that points to the correct url.

That should get it on the server.

Use

@ini_set( 'upload_max_size' , '64M' );

in functions.php if you file size limit is too low.

Then something like this in to handle the file:


add_action('wp_ajax_nopriv_canvasUpload', 'canvasUpload');
add_action('wp_ajax_canvasUpload', 'canvasUpload');

function canvasUpload(){
$uploads = wp_upload_dir();
$img = $_POST['uploadImage'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $uploads['path'].'/'. uniqid() . '.png';
$r = file_put_contents($file, $data);
echo $r ? $file : 'Error saving file';
}


User179751 comments:

thanks worked perfectly. will have to review my code to see what I had done but thank you.

2019-06-08

Arnav Joy answers:

Can you please show me url of the site ?

2019-06-08

Hugo Gonçalves answers:

Hi!

Have you tried changing the upload size limit?

Both in the server settings and WP itself, to handle larger files.
There are multiple ways to get about this.

1- Server file size limit:
Have no idea what your server setup is, but in broader terms you can:
A: change it under CPanel, in the PHP current version page

or

B: or you can drop a php.ini file with the following:
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300


or

C: You can also add to the htaccess file:
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300


2- Wordpress file size limit:
In the wp-config.php file add the following:
define('WP_MEMORY_LIMIT', '64M');

Let me know of any doubts or if it worked.

Thank You
Hugo Gonçalves

2019-06-08

Bob answers:

As other Masters suggested have you tried increasing upload file size limits?
is image in png format? Creating it in jpeg will reduce the size I think.

Have you tried with lower quality jpeg images first?
canvas.toDataURL('image/jpeg', 0.5);