-4

Here's my code- I want to upload image file and show it in the image div. I want to trigger ajax code written in js when i select a file.It should upload file to server and show it without any other event. But this code is not working. It is showing that undefined index image, instead of image.

HTML FORM

  <!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 file-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';
 }


 ?>
SONIA JOHNSON
  • 37
  • 1
  • 6

2 Answers2

0

At javascript you can set .responseType to "blob", use 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);
    }
  };
}

at php use file_get_contents()

echo file_get_contents("upload/" . $newFilename);
guest271314
  • 1
  • 15
  • 104
  • 177
0

 
  var file = document.getElementById("File_1").files[0];
  var data = new FormData();
  data.append("image", file);
  var xhttp = new XMLHttpRequest(); 
  xhttp.open("POST", "--Url--", true);
  xhttp.responseType = "blob";
  xhttp.send(data);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) { 
      document.getElementById("Image_File").src = URL.createObjectURL(xhttp.response);
    }
  };