I'm trying to make a image preview function using Ajax.
When I was trying I have some questions pop up:
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."'>";
?>
Here to add in image preview https://jsfiddle.net/bhx0s2dh/2/
It is not that hard to use filereader.
HTML
<input id="image" type="file" multiple></input>
<div id="image-preview"></div>
Javascript
$('#image').change(function () { //whenever the input changes
PreviewImage(this);
});
function PreviewImage(source) {
if ( !! window.FileReader) { //check if browser supports file reader
$('#image-preview').html(''); //wipe the preview container
var files = source.files; //get the file from the input
for (var i = 0; i < files.length; i++) {
var file = files[i].name; //get the file name *if you need it*
$reader = new FileReader(); //initialize file reader
$reader.readAsDataURL(files[i]); //read the file
$reader.onload = function (e) { //load the result
$('#image-preview').append('<div class="images"><img src="' + e.target.result + '" ></div>');
//e.target.result is the src
}
}
}
}
CSS
.images {
float:left;
}
.images img {
width:auto;
height:auto;
max-width:200px;
max-height:200px;
}