上传图片已损坏

时间:2019-11-07 17:27:11

标签: javascript php html mysql

我正试图允许用户通过单击旧的个人资料图片来上传新的个人资料图片。

我正在使用ajax和文件阅读器

$('#profileImage').click(function(){ $('#image-file').trigger('click'); });

                $('#image-file').on('change',function(){
                    if (this.files && this.files[0]) {

                        var FR= new FileReader();

                        FR.readAsDataURL(this.files[0]);                    
                        FR.addEventListener("load", function(e) {
                          document.getElementById("profileImage").src = e.target.result;

                          imgData = e.target.result;

                          var formData = {
                            'name'              : localStorage.getItem('email'),
                            'image'             : imgData
                          };

                            console.log("image data: " + imgData);


                            $.ajax({
                                 type   : 'POST',
                                 url    : '/uploadprofile.php',
                                 data   : formData,
                                 dataType: 'text',
                                 encode : true
                            }).done(function(data) {
                                  console.log(data);
                            });


                        });
                    }





                });   

新图像将被加载到旧图像上,并且控制台将跟踪通过其发送的图像数据。 唯一的问题是容器不可见新更新的图片。它显示了残破图片的图标。 这是我的php文件,用于处理插入

$json = json_decode(file_get_contents('php://input'),true);


    if ($json == "") {
        $name = $_POST['name'];
        $image = $_POST['image'];
    } else {
        $name = $json["name"]; //within square bracket should be same as Utils.imageName & Utils.image

        $image = $json["image"];
    }




    $response = array();

    $decodedImage = base64_decode("$image");

    //unlink old picture
    // unlink($name.".jpg");
    $oldName = $name;
    $name .= date("D M d Y G:i");
    $name = str_replace(' ', '', $name);

    $fullPath = "http://www.mywebsite.com/uploads/".$name.".jpg";

    $return = file_put_contents("uploads/".$name.".jpg", $decodedImage);

    if($return !== false){
        $response['email'] = $oldName;
        $response['image'] = $image;
        $response['success'] = 1;
        $response['message'] = "Image Uploaded Successfully";
        $sql = "UPDATE Users SET PicLocation = '$fullPath' WHERE Email = '$oldName'";

        $result = $conn->query($sql);
    }else{
        $response['success'] = 0;
        $response['message'] = "Image Uploaded Failed";
    }

    echo json_encode($response);

已打印出的$ response ['image']值正确,但似乎没有显示图片。数据以某种方式损坏。我应该做些什么来获取正确的数据? 此外,有时我会收到错误消息:

  

jquery.min.js:2 POST http://tanglecollege.com/uploadprofile.php 406(不可接受)

我不知道这意味着什么,而且似乎没有很好的解释。

此外,保存到服务器的文件在某种程度上已损坏。我可以跟踪从js传递到php的base64数据,但是当将其保存为文件时,该文件已损坏,无法从文件路径读取图像。

0 个答案:

没有答案
相关问题