上传图像并从php获取响应并重新加载相同的图像。 AJAX上传

时间:2013-02-19 12:08:01

标签: php jquery ajax file-upload

我有一个个人资料页面,其中默认图片为(no_image.jpg)。在其下方有一个用户可以上传他的图像​​的选项。一旦用户选择了图像并在对话框中单击“打开”,图像就会上传到服务器,响应应该用他的新图像替换(no_image.php)。我尝试谷歌搜索和堆叠我需要的确切输出。但我找不到。

style

#upload_progress {display:none;}

HTML

 <div id="upload_progress">
    </div>
<form enctype="multipart/form-data" method="post" action="">
        <input type="file" name="file" id="file" onchange="uploadFile()"/>
        <input type="submit" name="submit" />
    <form> 

js

var handleUpload = function(event){
    event.preventDefault();
    event.stopPropagation();

    var fileInput = document.getElementById('file');

    var data = new FormData();

    data.append('ajax', true)
        data.append('file', fileInput.files);


    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(event){
        if(event.lengthComputable){
            var percent = event.loaded  /event.total;
            var progress = document.getElementById('upload_progress');

            while(progress.hasChildNodes()){
                progress.removeChild(progress.firstChild);
            }
            progress.appendChild(document.createTextNode(Math.round(percent*100) + '%'))
        }
    });

    request.upload.addEventListener('load', function(event){
        document.getElementById('upload_progress').style.display = 'none';
    });

    request.upload.addEventListener('error', function(event){
        alert('upload failed');
    });

    request.addEventListener('readystatechagne', function(event){
        if(this.readyState == 4){
            if(this.status == 200){
                var links = document.getElementById('uploaded');

                console.log(this.response);
                var uploaded = eval(this.response);

                var div, a;

                div = document.createElement('div');
                a = document.createelement(a);

                a.setAttribute('href', 'files/'+uploaded);
                a.appendChild(document.createTextNode(uploaded[i]));

                div.appendChild(a);
                links.appendChild(div);

            }else{

            }
        }
    });

    request.open('POST', '/profile');
    request.setRequestHeader('Cache-Control', 'no-cache');

    document.getElementById('upload_progress').style.display = 'block';
    request.send(data);
}

window.addEventListener('load', function(event){
    var submit = document.getElementById('submit');
    submit.addEventListener('click', handleUpload);
});

PHP

if($_FILES['file'] != '')
{
    //print_r($_FILES);

        $filename = basename($_FILES['file']['name']);

        $sqlUpdate  =   mysql_query("UPDATE tableA SET user_img = '".$filename."' WHERE email = '".$userEmail."'");
        $newname = '\images\profile/'.$filename;

        if($_FILES['file']['error'] == 0 && move_uploaded_file($_FILES['file']['tmp_name'], $newname));
        $Uploaded = $filename;
}

if(!empty($_POST['ajax'])){
    die(json_encode($Uploaded));
    exit();
}

帮助者将不胜感激。在此先感谢!! ...

1 个答案:

答案 0 :(得分:2)

据我所知(可能是我的知识已经过时)你无法通过AJAX发送图像。

将表单更改为

<iframe id="hiddenIframe"></ifram>
<form enctype="multipart/form-data" method="post" action="pageGettingData.php" target="hiddenIframe">
    <input type="file" name="file" id="file" onchange="uploadFile()"/>
    <input type="submit" name="submit" />
<form> 

并在uploadFile()函数中使用将提交表单的代码。

现在数据将作为普通表单上传,但会上传到隐藏的iframe,不会导致任何重定向等。

PHP代码中的

if($_FILES['file'] != '')
{
    //print_r($_FILES);

        $filename = basename($_FILES['file']['name']);

        $sqlUpdate  =   mysql_query("UPDATE mp_project_buyer_query SET user_img = '".$filename."' WHERE email = '".$userEmail."'");
        $newname = '\images\profile/'.$filename;

        if($_FILES['file']['error'] == 0 && move_uploaded_file($_FILES['file']['tmp_name'], $newname));
        $Uploaded = $filename;

        echo '<script>parent.updateImage("' . $Uploaded . '");'; // add a javascript
}

if(!empty($_POST['ajax'])){
    die(json_encode($Uploaded));
    exit();
}

现在,当php获取一个图像时,它将调用一个JS函数,因为JS在隐藏的Iframe中我们想要在父文件上调用该函数。

在HTML文件中

创建一个新的JS函数updateImage

function updateImage(imgPath){
    $('#userImage").attr('src': imgPath);
}

此JS将使用新上传的图像路径更新图像路径。您可能必须修复变量和图像路径才能使其正常工作。我刚刚写了很快