如何使用ajax上传图像并使用pdo在mysql中保存图像地址

时间:2017-07-08 15:58:13

标签: php jquery ajax

如何上传图片并将图片地址保存在mysql中? 1.我想用AJAX上传图片 2.图像地址将与pdo一起存储在mysql中 这是我的代码:

$(document).ready(function(){
    $("#usredit").click(function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var file = $("#file").val();
        var image = $("#image").val();
        var id = $("#id").val();
        var send = true;
        $.post("set-ajax.php",{name:name,email:email,file:file,image:image,id:id,send:send},function(data){
                    $("#editres").html(data);
        });
    });
});

ajax.php

if(isset($_POST['send'])){
    if(empty($_POST['name']) || empty($_POST['email'])){
        echo '<div class="alert alert-warning">Fill empty fields</div>';
            }else{
                if(isset($_POST['file'])){
                    $file = $_POST['file'];
                    $tmp = $_FILES['file']["tmp_name"];
                    $name = $_FILES['file']['name'];
                    $type = $_FILES['file']['type'];
                    if (is_uploaded_file($tmp)){
                        $ext = array("image/jpg","image/png","image/jpeg");
                        if (in_array($type,$ext)){
                            $filename = md5($name.microtime()).substr($name,-5,5);
                        if(move_uploaded_file($tmp,"user/img".$filename)){
                            echo '<div class="alert alert-success">Upload done</div>';
                        }else{
                                echo '<div class="alert alert-warning">Upload failed</div>';
                            }
                        }else{
                            echo '<div class="alert alert-warning">Unrelated file</div>';
                        }
                    }
                }
                $name = $_POST['name'];
                $email = $_POST['email'];
                $image = $_POST['image'];
                $id = $_POST['id'];
                $resualt = $User->UpdateUserProfile($name,$email,$image,$id);
                if($resualt ){
                    echo '<div class="alert alert-success">Edit done</div>';
                }else{
                    echo '<div class="alert alert-warning">Edit failed</div>';
                }
            }

1 个答案:

答案 0 :(得分:0)

假设您可以将图片上传到user/img文件夹。然后,创建一个更新/插入上传图像细节的方法。并通过传递图像名称来调用该方法(因为,文件夹路径将是所有人共同的)

      if(move_uploaded_file($tmp,"user/img".$filename)){
            // update/insert table with folder location.
            // call the method here             
           echo '<div class="alert alert-success">Upload done</div>';
        }