jQuery Ajax Post Image Multipart

Bagaimana cara post file atau gambar menggunakan jquery ajax? Lihat selengkapnya.
978  
       

Dalam pembahasan kali ini, akan dipaparkan bagaimana cara post file atau gambar menggunakan jquery ajax. Hal ini sebetulnya untuk yang sudah pernah mencoba akan terasa sangat gampang. Namun, untuk yang baru memulai akan sangat ribet.

Kebutuhan Dasar

Pertama-tama sebelum melanjutkan membaca artikel, ada beberapa hal yang harus dipahami terlebih dahulu. Pertama, jQuery ajax merupakan aplikasi yang dijalankan dalam Dua Alam ada web biasa (frontend) dan ada API service provider untuk backendnya.

Kedua, diasumsikan kode didalam frontend menggunakan Bootstrap atau Foundation secara standar. Adapun komponen yang digunakan yaitu komponen modal. Dimana nantinya form tersebut hanya akan muncul jika telah dipicu dengan klik atau aksi lainnya.

Ketiga untuk backend akan digunakan framework Code Igniter atau Seme Framework. Dalam pembahasan kali ini digunakan adalah seme framework. Dimana Seme Framework ini hanya digunakan untuk backend saja. Diasumsikan semua model dan database sudah tersedia. Yaitu model mc_file yang isinya akan ada atribut untuk pengelolaan file.

Tahap Javascript

Berikut ini adalah cara untuk melakukan post image menggunakan jQuery Ajax.

$("#fuploader").on("submit",function(e){
        $("#ploading").hide(); //menampilkan elemen p loading;
	e.preventDefault();
	$.ajax({
		type: frm.attr('method'), //ngambil dari form method
		url: frm.attr('action'),  //ngambil dari form action
		data: new FormData(this), //buat ngambil isi dari form
		contentType: false,       
		cache: false,             
		processData:false,        
		success: function(data){ 
			console.log(d);
			if(d.status==1 || d.status=="1"){ //tergantung dari response APInya. Dalam kasus ini cuman ada dua objek json. status, sama result-> isinya pesan.
				shTable.ajax.reload();
				$("#modal_uploader").modal("hide"); //hide modal jika ada
				setTimeout(function(){

					jQuery.gritter.add({ //jika menggunakan jquery gritter, hapus aja atau ganti sama alert('berhasil');
						title: 'Berhasil',
						text: 'Data Barang Hilang berhasil ditambahkan',
						//class_name: 'growl-info',
						image: 'images/comment.png',
						sticky: false,
						time: ''
					});
				}, 666);
				
			}else{
				$("#ploading").html(d.result); //ini untuk memperlihatkan result ke tag p
				$("#ploading").show(); //menampilkan elemen p loading;
			}
		}
	});
	
});

Tahap HTML / Frontend

Setelah melihat koding JavaScriptnya, mari kita coba lihat file htmlnya. Diasumsikan formnya berada dalam sebuah modal.

Dari kode html tersebut ada penambahan

yang secara default di hidden untuk menunjukan status atau error pada saat proses selesai.

Tahap API / Backend

Bagaimana di sisi API? mari kita lihat. Berikut ini adalah potongan kode untuk upload dan insert ke database.

<?php
<?php class Uploader extends SENE_Controller{ var $status = 0; var $module = "uploader"; var $treehtml = ''; var $apikeycollection; public function __construct(){ parent::__construct(); $this->lib("SENE_JSON_Engine","lib");
		$this->load("seme_purifier","lib");
		$this->lib("site_config","lib");
		$this->load("mc_file");
		$this->lib("sene_upload_wide_image","lib");
		$this->apikeycollection = array("xx","xx");
	}	
	public function index(){
		header("Content-Type: application/json");
		echo json_encode(array("status"=>1,"result"=>"Welcome to seme framework!");
	}
	public function add(){
		/*******************************************************
		 * Only these origins will be allowed to upload images *
		 ******************************************************/
		$ifol = realpath(SENEROOT.DIRECTORY_SEPARATOR.$this->site_config->cms_media.DIRECTORY_SEPARATOR);
		//die($ifol);

		reset($_FILES);
		$temp = current($_FILES);
		if (is_uploaded_file($temp['tmp_name'])){
			if (isset($_SERVER['HTTP_ORIGIN'])) {
				// same-origin requests won't set an origin. If the origin is set, it must be valid.
				header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
			}
				header('Access-Control-Allow-Credentials: true');
				header('P3P: CP="There is no P3P policy."');

			// Sanitize input
			if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
					header("HTTP/1.0 500 Invalid file name.");
					return;
			}
			// Verify extension
			if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
					header("HTTP/1.0 500 Invalid extension.");
					return;
			}

			// Create magento style media directory
			
			$name  = $temp['name'];
			$name1 = $name{0};
			$name2 = $name{1};
			if(!is_dir($ifol)) mkdir($ifol,0775);
			$ifol = $ifol.DIRECTORY_SEPARATOR.$name1.DIRECTORY_SEPARATOR;
			if(!is_dir($ifol)) mkdir($ifol,0775);
			$ifol = $ifol.DIRECTORY_SEPARATOR.$name2.DIRECTORY_SEPARATOR;
			if(!is_dir($ifol)) mkdir($ifol,0775);
			
			// Accept upload if there was no origin, or if it is an accepted origin
			
			$filetowrite = $ifol . $temp['name'];
			move_uploaded_file($temp['tmp_name'], $filetowrite);

			// Respond to the successful upload with JSON.
			// Use a location key to specify the path to the saved image resource.
			$label = $name;
			$url = $name;
			$folder = $this->input->post("folder");
			if(empty($folder)) $folder = "/";
			$res = $this->mc_file->setNew($label,$url,$folder,$is_active=1);
			header("Content-Type: application/json");
			echo json_encode(array('id'=>$res,'location' => base_url("media/cms/".$name1."/".$name2."/".$name), 'folder'=>$folder));
		} else {
			// Notify editor that the upload failed
			header("HTTP/1.0 500 Server Error");
		}
	}

Demikian Semoga membantu.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>