在上传之前调整大小并使用ajax使用formData发送

时间:2014-03-09 13:28:22

标签: javascript php ajax html5

我已经完成了我的php后端调整大小,现在我也在使用JS工作在前端。下面是一个工作脚本,但它使用$ _POST,我试图使用formData附加数据,不工作。数据甚至不发送..

function resizeAndUpload(file) {
var reader = new FileReader();
    reader.onloadend = function() {

    var tempImg = new Image();
    tempImg.src = reader.result;
    tempImg.onload = function() {

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var tempW = tempImg.width;
        var tempH = tempImg.height;
        if (tempW > tempH) {
            if (tempW > MAX_WIDTH) {
               tempH *= MAX_WIDTH / tempW;
               tempW = MAX_WIDTH;
            }
        } else {
            if (tempH > MAX_HEIGHT) {
               tempW *= MAX_HEIGHT / tempH;
               tempH = MAX_HEIGHT;
            }
        }

        var canvas = document.createElement('canvas');
        canvas.width = tempW;
        canvas.height = tempH;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, tempW, tempH);
        var dataURL = canvas.toDataURL("image/jpeg");

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(ev){
            document.getElementById('filesInfo').innerHTML = 'Done!';
        };

        xhr.open('POST', 'uploadResized.php', true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var data = 'image=' + dataURL;
        xhr.send(data);
      }

   }
   reader.readAsDataURL(file);
}
然而,后端使用$ _post

if ($_POST) {
    define('UPLOAD_DIR', 'uploads/');
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.jpg';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
}

1 个答案:

答案 0 :(得分:0)

if (isset($_POST['image'])) {
define('UPLOAD_DIR', 'uploads/');

$uid = uniqid(md5(mt_rand(10,10000)), true); // this is our unique ID 

$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);

$image = imagecreatefromstring($data); /* we need this function to create the virtual image in memory */

header('Content-type: image/jpeg'); /* header is mandatory for img creation on disk (by     imagejpeg()) */

imagejpeg($image, UPLOAD_DIR.$uid.'.jpg'); /* this will 'write-down' the actual image into your upload directory */

imagedestroy($image); /* destroy the tmp image after real image is created on your upload dir */ 

/* to get all that stuff running - check your upload dir if is set to be writeable */

}