2016-07-23 58 views
-4

這裏是我的代碼 - 我要上傳圖片文件,並顯示在圖像DIV。 我想觸發寫在JS AJAX代碼時,我選擇file.It應上傳文件到服務器並顯示它沒有任何其他事件。 但是這段代碼不起作用。它顯示的是未定義的索引圖像,而不是圖像。如何在JavaScript中使用AJAX上傳圖片?

HTML表單

<!doctype html> 
    <html> 

<body> 
<div id="wb_Image2> 
<img src="" id="Image2" alt=""> 
</div> 


    <input type="file" id="FileUpload1" name="image" onchange="upload()" > 
    <div id="div"> </div> 





</body> 
</html> 

JS FILE-

function upload() 
    { 


    var xhttp = new XMLHttpRequest(); //creating a xmlhttp request; 

    xhttp.open("POST","upload.php", true); 
    xhttp.send(); 
    xhttp.onreadystatechange = function() 
    { 
if (xhttp.readyState == 4 && xhttp.status == 200) 
    { 
alert(xhttp.responseText); 
document.getElementById("div").innerHTML= xhttp.responseText; 
document.getElementById("Image2").src = xhttp.responseText; 
    } 
    }; 


} 

PHP文件upload.php的

<?php 
    $errors=array(); 
$name=$_FILES['image']['name']; //storing name of d file 
    $ext=explode('.',$name); //ext[0]=nameOfFile and ext[1]= extension 
$size=$_FILES['image']['size'];//storing size 
    $tmpName=$_FILES['image']['tmp_name'];//storing temp name 

    $validExt=array("jpg","jpeg","png","gif");//valid extensions 

if(($size/(1024*1024))>2) //checking file size is less than 2mb or not 
{ 
$errors[]="file size exceeds 2 mb"; 
    echo "file size exceeds 2 mb"; 
} 
    if(empty($errors)) 
{ 
echo $ext[0]." ".$ext[1]; 

$newFilename = $ext[0].substr(session_id(),0,5).rand(0,1000).".".$ext[1]; 
move_uploaded_file($tmpName,"upload/".$newFilename); 


    } 
else { 
echo 'flag 1'; 
} 


?> 
+0

http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – adeneo

回答

0

javascript可以設置.responseType"blob",使用URL.createObjectURL()

function upload() { 
    var file = document.getElementById("FileUpload1").files[0]; 
    var data = new FormData(); 
    data.append("image", file); 
    var xhttp = new XMLHttpRequest(); //creating a xmlhttp request; 
    xhttp.open("POST", "upload.php", true); 
    xhttp.responseType = "blob"; 
    xhttp.send(data); 
    xhttp.onreadystatechange = function() { 
    if (xhttp.readyState == 4 && xhttp.status == 200) { 
     // alert(xhttp.responseText); 
     // document.getElementById("div").innerHTML = xhttp.responseText; 
     document.getElementById("Image2").src = URL.createObjectURL(xhttp.response); 
    } 
    }; 
} 

在PHP中使用file_get_contents()

echo file_get_contents("upload/" . $newFilename); 
+0

thanks..but具有u測試它? –

+0

@TusharSah測試哪個部分?不確定你的意思?您可以'echo'文件的內容,在'javascript'過程'Blob'響應 – guest271314

+0

爵士,它仍然沒有工作 –