简体   繁体   中英

Having an issue whilst saving JPEG, from html5 canvas, to server

I have an image loaded to the browser in a HTML canvas wrapper.

<canvas id="image1" class="" width="213" height="213" style="width: 213px; height: 213px;"></canvas>

When I try to save this to the server via AJAX, it works fine but when the file is a JPEG, it doesn't redirect from the AJAX.

Here's my ajax

var imageName = $('#image_name').val();
var canvas = document.getElementById('image1');

var dataURL = canvas.toDataURL();       
$.ajax({
    type: "POST",
    url: "script.php",
    data: { 
            imgBase64: dataURL                          
        }
    }).done(function(data) {
        alert(data);
       window.location.replace("http://****.co.uk/dither/step3.php?id="+data)
    });

Here's my php

<?php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
echo $file;
?>

If the image is a png file, then the redirect works, but if it's a JPEG it just returns back to the same page.

If I alert the 'dataURL' before the ajax call it returns a array with the first part as 'data:image/png;base64' no matter what type of file extension.

I don't know enough about the base64 stuff to figure this out.

由于 javascript 是异步的,ajax 在文件上传完成之前就被触发,这就是它失败的原因。

Use this sample of code to create create image from string, this will fix the issue

imagecreatefromstring($n) then imagejpeg($r,$y) or imagepng($r,$y);

and

imagedestroy($r);

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