dora1989 2016-09-23 18:54
浏览 41

Ajax DataUrl到PHP

I am stuck here, i think i am close but not sure. this is what i have managed to come up with. Created file input, then resized image then try to upload new image to folder in server. i think my php script is communicating, but not recieving any image. here is the code below..

FORM

<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">

JAVASCRIPT

<script>
function handleFiles(){
var dataurl = "";
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];

// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
    img.src = e.target.result;

    var canvas = document.createElement("canvas");
    //var canvas = $("<canvas>", {"id":"testing"})[0];
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var MAX_WIDTH = 400;
    var MAX_HEIGHT = 300;
    var width = img.width;
    var height = img.height;

    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);

    dataurl = canvas.toDataURL("image/jpeg");     
}
// Load files into file reader
reader.readAsDataURL(file);

        // Post the data
        var fd = new FormData();
        fd.append("name", "some_filename.jpg");
        fd.append("image", dataurl); // blob file
        fd.append("info", "lah_de_dah");
        $.ajax({
            url: 'http:///www.***/upload.php',
            data: fd,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
                $('#form_photo')[0].reset();
                location.reload();
}

});
}
</script>

SERVER SIDE PHP

<?php
$upload_image = $_FILES["image"][ "name" ];
$a = ('" alt="" />');
$folder = "images/";
move_uploaded_file($_FILES["image"]["tmp_name"], "$folder".$_FILES["image"]["name"]);;

$file = 'images/'.$_FILES["image"]["name"];

$uploadimage = $folder.$_FILES["image"]["name"];
$newname = $_FILES["image"]["name"];

$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$a = ('" alt="" />');
$image = $_FILES['image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('**','**','**','**') or die('Unable To connect');
$sql = ("INSERT into links (hyper_links) VALUES('<img src=\"\https://www.***/images/".$_FILES['image']['name']."$a')");

$stmt = mysqli_prepare($con,$sql);

mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);

$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
    $msg = 'Successfullly UPloaded';
}else{
    $msg = 'Could not upload';
}
mysqli_close($con);
}
?>
<?php
echo $msg;
?>

My PHP script might out of wack as i originally was resizing image through PHP, so i just removed what i thought was not needed for the example. The question is i am not sure how to handle the new image to the server.p

  • 写回答

1条回答 默认 最新

  • douzhang5121 2016-09-24 08:23
    关注

    First of all: You shouldn't upload the image as base64. Just send the raw binary instead. So use canvas.toBlob() and maybe some polyfill

    canvas.toBlob(function(blob){
        fd.append('image', blob, 'some_filename.png')
    })
    

    Otherwise PHP won't notice any $_FILES cuz base64 will be treated as just any other field $_POST field

    Second is just a tip: you can use URL.createDataURL instead of using the FileReader and you probably should use img.onload and img.onerror also

    by ditching the FileReader you just do this:

    img.onload = function(){
        // paint to canvas
    }
    img.onerror = function(){
        // meh, not a image
    }
    img.src = URL.createObjectURL(file)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)