简体   繁体   中英

Base64 image send through Ajax encodeURIComponent

I'm trying send base64 converted image through ajax to a PHP backend. I have used encodeURIComponent for encode the base64 image and also I have to use encodeURI to encode the the parameters. Otherwise it keep giving me 403 Access denied error. When I send image like that image getting corrupt. When I just use encodeURIComponent to encode the image. and send without encode the parameters using encodeURI it works perfectly.(only in the local server.)

Following code only works in the local server (wamp)

                var img = canvas.toDataURL("image/png");

                var Parameters = "image=" + encodeURIComponent(img) + "&filename=" + name;

                $.ajax({
                    type: "POST",
                    url: "savePNG.php",
                    data: Parameters,
                    success: function (response) {
                        alert(response);
                    }
                });

And when I encode the data: encodeURI(Parameters), again it parse the data to the backend. but image get corrupt (I think because it encode two times.)

PHP backend code is like following.

$image = $_POST['image'];

$filename = $_POST['filename'];

$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);

file_put_contents($filename . ".png", $decoded, LOCK_EX);

echo $image;

Is there a way to make in work on the server without image getting corrupt.

Use following trick.

JavaScript

var img = canvas.toDataURL("image/png");

var ajax = new XMLHttpRequest();
ajax.open("POST", 'savePNG.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(img);

PHP Code

$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen("filename.png", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM