Note that there are some explanatory texts on larger screens.

plurals
  1. POSending images from Canvas elements using Ajax and PHP $_FILES
    primarykey
    data
    text
    <p>I need to be able to send an image and some form fields from a client side canvas element to a PHP script, ending up in $_POST and $_FILES. When I send it like this:</p> <pre><code>&lt;script type="text/javascript"&gt; var img = canvas.toDataURL("image/png"); ... ajax.setRequestHeader('Content-Type', "multipart/form-data; boundary=" + boundary_str); var request_body = boundary + '\n' + 'Content-Disposition: form-data; name="formfield"' + '\n' + '\n' + formfield + '\n' + '\n' + boundary + '\n' + 'Content-Disposition: form-data; name="async-upload"; filename="' + "ajax_test64_2.png" + '"' + '\n' + 'Content-Type: image/png' + '\n' + '\n' + img + '\n' + boundary; ajax.send(request_body); &lt;/script&gt; </code></pre> <p>$_POST and $_FILES both come back populated, but the image data in $_FILES still needs decoding like this:</p> <pre><code>$loc = $_FILES['async-upload']['tmp_name']; $file = fopen($loc, 'rb'); $contents = fread($file, filesize($loc)); fclose($file); $filteredData=substr($contents, strpos($contents, ",")+1); $unencodedData=base64_decode($filteredData); </code></pre> <p>...in order to save it as a readable PNG. This isn't an option as I'm trying to pass the image to Wordpress's media_handle_upload() function, which requires an index to $_FILES pointing to a readable image. I also can't decode, save and alter 'tmp_name' accordingly, as it falls foul of security checks.</p> <p>So, I found this: <a href="http://www.webtoolkit.info/javascript-base64.html" rel="noreferrer">http://www.webtoolkit.info/javascript-base64.html</a> and tried to do the decode on the client side:</p> <pre><code>img_split = img.split(",",2)[1]; img_decoded = Base64.decode( img_split ); </code></pre> <p>but for some reason I still don't end up with a readable file when it gets to the PHP. So the question is: "Why?" or "What am I doing wrong?" or "Is this even possible?" :-)</p> <p>Any help very much appreciated!</p> <p>Thanks, Kane</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload