I'm trying to make a image preview function using Ajax.
When I was trying I have some questions pop up:
- when the Ajax had runned, does the image itself has been uploaded to the server? Or just an array has been sent including strings name, type, size, tmp_name?
- the code below returns a broken image icon.
I have tried:
HTML file:
<script type="text/javascript" src="/script/googleapis.js"></script>
<input multiple type="file" id="myFile" size="50">
<div id="sub">submit</div>
<div id="testtest"></div>
<script>
$("#sub").click(function(){
// get the file objects
var files = $("#myFile")[0].files,
data = new FormData;
for (var i = 0; i < files.length; i++){
//test if the files[i] has the file objects
console.log(files[i]);
//post objects to another php file
data.append('img[]', files[i]);
}
$.ajax({
url: "testphp.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result){
$("#testtest").html(result);
}
});
});
</script>
PHP file (test.php)
<?php
$file_name=$_FILES['img']['name'][0];
$file_tmp=$_FILES['img']['tmp_name'][0];
var_dump($file_tmp); // for test if the variable has been post successfully
echo "<img src='".$file_tmp."'>";
?>