【问题标题】:Uploading Image and getting response from php and reloading the same image. AJAX Upload上传图像并从 php 获取响应并重新加载相同的图像。 AJAX 上传
【发布时间】:2013-02-19 12:08:00
【问题描述】:

我有一个个人资料页面,其中默认图像为 (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();
}

帮助者将不胜感激。提前致谢!!...

【问题讨论】:

    标签: php jquery ajax file-upload


    【解决方案1】:

    据我所知(可能是我的知识已经过时)您不能通过 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会用新上传的图片路径更新图片路径。您可能必须修复变量和图像路径才能使其工作。我只是快速写了它们

    【讨论】:

    • 使用XHR2,您可以通过 Ajax 处理文件。所以不再需要这个iframe-solution ;-) html5rocks.com/en/tutorials/file/xhr2
    • 我在文件中犯了一个小错误。所以我从早上开始就在和它打架,最后我来堆叠。现在我发现它通过 ajax 进行。你的回答会很好用。感谢您的努力。!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 2017-01-28
    • 1970-01-01
    • 2015-05-30
    • 2014-11-17
    相关资源
    最近更新 更多