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

douge3830
douge3830 只有将SQL插入放入数据库而没有图像名称这一事实。数据应该显示imgsrc链接,这就是为什么我认为它在某种程度上与知道错误有关
大约 4 年之前 回复
doutang7707
doutang7707 只是确保你的表单上有enctype='multipart/form-data'?
大约 4 年之前 回复
doulierong0334
doulierong0334 我知道了。我解决了工作问题的个人问题。是什么让你认为它现在部分工作(在PHP中)?
大约 4 年之前 回复
doumeng1089
doumeng1089 我还将dataurl=“null”更改为dataurl=“”;
大约 4 年之前 回复
dongmu6578
dongmu6578 我不得不将这个<scriptsrc=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js></script>添加到正文中。我目前正在使用html5程序来构建我的网络应用程序
大约 4 年之前 回复
dongqiang2024
dongqiang2024 似乎我甚至无法使JavaScript代码工作......这是HTML/JavaScript的所有代码吗?我可以尝试重新创建,看看它是怎么回事。
大约 4 年之前 回复

1个回答



首先:</ strong>您不应将图像上传为base64。 只需发送原始二进制文件即可。 因此,请使用 canvas.toBlob(),也许还有一些< a href =“https://github.com/eligrey/canvas-toBlob.js/"rel =”nofollow“> polyfill </ p>

  canvas.toBlob(  function(blob){
fd.append('image',blob,'some_filename.png')
})
</ code> </ pre>

否则PHP将不会注意到 任何$ _FILES cuz base64将被视为任何其他字段$ _POST字段</ p>

其次只是一个提示:</ strong>您可以使用 URL.createDataURL < / code>而不是使用FileReader,您可能应该使用 img.onload </ code>和 img.onerror </ code> </ p>

放弃FileReader 你只需要这样做:</ p>

  img.onload = function(){
// paint to canvas
}
img.onerror = function(){
// meh,not a image
}
img.src = URL.createObjectURL(file)
</ code> </ pre>
</ div>

展开原文

原文

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)

douchuanhan8384
douchuanhan8384 我无法让这个工作,可能是我对知识的使用,但我应该提一下,这需要在移动平台Chrome / safari上工作,因为它是我正在创建的网络应用程序
大约 4 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐