December 28th, 2009 by mbahsomo

Assalamu’ alaikum wr wb

Beberapa hari yang lalu ad seorang teman bertanya kepada saya gimana cara membuat program upload dengan AJAX dan php, setelah beberapa waktu baru hari ini luang.

Langsung pada permasalahan buat sebuah fodler pada htdocs kamu misal : latihanUpload pertama – tama buat script seperti di bawah ini :


<html>
 <head>
 <title></title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <script language="javascript">
 //Buat object untuk Ajax
 var http=createRequestObject();
 var uploader="";
 var uploadDir="";
 var dirname="";
 var filename="";
 var timeInterval="";
 var idname="";
 var uploaderId="";

 function createRequestObject() {
 var browser = navigator.appName;
 if(browser == "Microsoft Internet Explorer"){
 return new ActiveXObject("Microsoft.XMLHTTP");
 }
 else{
 return new XMLHttpRequest();
 }
 }
 //Untuk upload
 function traceUpload() {
 http.onreadystatechange = handleResponse;
 http.open("GET", 'imageupload.php?uploadDir='+uploadDir+'&dirname='+dirname+'&filename='+filename+'&uploader='+uploader);
 http.send(null);
 }

 function handleResponse() {
 if(http.readyState == 4){
 var response=http.responseText;
 if(response.indexOf("File uploaded") != -1){
 clearInterval(timeInterval);
 //document.getElementById('loading'+idname).innerHTML="";
 }
 document.getElementById(uploaderId).innerHTML=response;
 }
 else {
 document.getElementById(uploaderId).innerHTML="Uploading File. Please wait...";
 }
 }
 //Pemanggilan pertama pada fungsi upload
 function uploadFile(obj, dname) {
 uploadDir=obj.value;
 idname=obj.name;
 dirname=dname;
 filename=uploadDir.substr(uploadDir.lastIndexOf('\\')+1);
 uploaderId = 'uploader'+obj.name;
 uploader = obj.name;
 document.getElementById('formName'+obj.name).submit();
 timeInterval=setInterval("traceUpload()", 1500);
 }
 </script>
 </head>
 <body>
 <form id="formNameid1" method="post" enctype="multipart/form-data" action="imageupload.php?dirname=" target="iframeid1">
 <input type="hidden" name="id" value="id1" />
 <span id="uploaderid1" style="font-family:verdana;font-size:10;">
 Upload File: <input name="id1" type="file" value="id1" onchange="return uploadFile(this,'')" /></span>
 <span id="loadingid1"></span>
 <iframe name="iframeid1" src="imageupload.php" width="400" height="100" style="display:none"> </iframe>
 </form>
 </body>
</html>

Beri nama index.html

dan selanjutnya buat file imageupload.php


<?php
/**
 * This file uploads a file in the back end, without refreshing the page
 *
 */
@session_start();
$dirName="uploads";
//echo $_POST['id'] . '<br/>';
if (isset($_POST['id'])) {
 //$uploadFile=$_GET['dirname']."/".$_FILES[$_POST['id']]['name']; for security reasons,  hardcode the name of the directrory.
 @mkdir($dirName,0777);

 $uploadFile="$dirName/".md5($_FILES[$_POST['id']]['name'].".demo");

 if(!is_dir($_GET['dirname'])) {
 echo '<script> alert("Failed to find the final upload directory: $dirName);</script>';
 }
 if (!copy($_FILES[$_POST['id']]['tmp_name'], $dirName.'/'.md5($_FILES[$_POST['id']]['name'].".demo"))) {
 echo '<script> alert("Failed to upload file");</script>';
 }else {

 }
}else {
 // for secority reason either remove the extentions or rectrict uploaded not to upload / run scripts like file.php else they can misuse the disk space
 //$uploadFile=$_GET['dirname']."/".$_GET['filename']; // removed for security reasons (happend with my demo )
 $uploadFile="$dirName/".md5($_GET['filename'].".demo");
 if (file_exists($uploadFile)) {
 echo "File uploaded. <a href='$uploadFile'>Open File</a>";
 }
 else {
 echo "<img src='loading.gif' alt='loading...' />";
 }
}
?>

sekarang tinggal memanggilnya dengan ketik di URL addres kamu http://localhost/latihanUpload/

Ok sekarang selesai deh program uploadnya.

Wassalamu’ alaikum wr wb

Sumber : http://www.phpclasses.org/browse/package/2759.html#download

3 Responses to “PHP Ajax Upload”

Although running a business sounds cool and all that. But in fact, I think you have to form a schedule so that you don’t get too involved. I liked that stuff you talked about “life is balance”. Maybe hiring someone do your work is a smart idea.

warman says:

mas…
makasih informasinya…
bermanfaat bgt…
semoga allah membalas kebaikan mas…

mbahsomo says:

@ warman:
Terimakasih juga atas kunjungannya mas

Leave a Reply