通过javascript上传图像与PHP

时间:2014-10-27 17:02:34

标签: javascript php html ajax ajaxform

carica.html

<td>
    <input type="file" size="30" onchange="preview()" id="upload_immagine">
</td>
<td>
    <div id="divImmagine" > </div>
</td>

filejavascript.js

function preview() 
{
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
            document.getElementById("divImmagine").innerHTML=xmlhttp.responseText;
    }
    image=request.getParameter("upload_immagine");
    document.getElementById("divImmagine").innerHTML=image;
    xmlhttp.open("POST","stampaAnteprima.php", false);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("image="+image);
}

stampaAnteprima.php

<?php
    $file_temp=($_FILES['image']['tmp_name']);
    echo"$file_temp";
?>

javascript image=request.getParameter("upload_immagine");行没有返回任何内容。如何将值传递给php然后通过$_FILES['image']['tmp_name']读取文件实际上它将是图像?你有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这将允许您将文件发送到php。

您可以添加更多eventlisteners来显示上传进度和错误处理。

function UploadPhoto(){
    var file = document.getElementById('upload_immagine').files[0];
    var formdata = new FormData();
    formdata.append("image", file);
    var req = new XMLHttpRequest();
    req.addEventListener("load", function(event) { uploadcomplete(event); }, false);
    req.open("POST", "stampaAnteprima.php");
    req.send(formdata);
}
function uploadcomplete(event){
// Your php reply = event.target.responseText 
}