doutingyou2198 2013-02-19 12:08
浏览 33
已采纳

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

I am having one profile page where default image will be (no_image.jpg). Below that there is a option where user can upload his image. Once the user selected the image and click open in the dialog box, the image should upload to server and the response should replace the (no_image.php) with his new image. I tried googling and stacking for the exact output i need. But i cannot find that.

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();
}

Helpers would be appreciated. Thanks in Advance !!...

  • 写回答

1条回答 默认 最新

  • dongyang9813 2013-02-19 12:16
    关注

    Well as far as I know (may be my knowledge is outdated) You can not send image via AJAX.

    Change your form to

    <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> 
    

    and in uploadFile() function use the code which will submit the form.

    Now data will be uploaded as a normal form, but to a hidden iframe which will not cause any redirect etc.

    in your PHP code

    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();
    }
    

    Now when php will get an image it will call a JS function, as that JS is in the hidden Iframe we want to call the function on the parent file.

    in your HTML file, create a new JS function updateImage

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

    this JS will update the image path with the newly uploaded image path. You may have to fix the variables and the image paths to make it work. I just wrote them quickly

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号