Example Script to Upload multiple Files

we can not using html alone to upload file from safari or new version android anymore , may be it because of security issue . but it make hard time for us the programmer

so I have a technic to share

I using a java-script to help read the selected files, even from the mobile camera .

yes “READ THE FILES” !!

that is the technic that i talking about . read the files one by one . get the file name , get the data in the base64 and then send data to the php script that waiting to write the file

“writer.php” is the php script will change the data back to binary and write it down in the specific folder.


so ready to see the code ?

this one we can call “upload.html”.

<script type="text/javascript">
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var fname = file.name;
var picReader = new FileReader();
picReader.addEventListener("load", function(event) {
var picFile = event.target;
var kk=picFile.result;
var data = new FormData();
data.append("data" , kk);
data.append("file_name" , fname);
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', 'writer.php', true );
xhr.send(data); });
picReader.readAsDataURL(file);
}
});
}
}
</script>

<input type=’file’ id=’uploadImage’ name=’file_input’ multiple=true >


and this is the “writer.php”

<?php

if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = $_POST['file_name'];
if(empty($fname)) $fname="tmp.bin";
$aa= strpos($data,",");
$body=substr($data,$aa+1);
$jpg=base64_decode($body);
$file = fopen("upload/$fname","w");
fwrite($file,$jpg);
fclose($file);
}

?>