[TIP] JQuery와 PHP로 이미지 파일을 업로드 하는 간단한 소스 (How to upload image file on PHP server by using JQuery)
- 파이팅건맨
- Apr 03, 2015
- 5573
JQuery를 이용하여 이미지 파일을 업로드 하는 간단한 코드입니다.
This is the way how to upload image file on PHP server by using JQuery.
HTML 내용
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="utf-8" /> <script src="http://code.jquery.com/jquery.min.js"></script> </head> <body> <script type="text/javascript"> $(document).ready(function() { $("#myform").submit( function(e){ e.preventDefault(); var datas, xhr; datas = new FormData(); datas.append( 'service_image', $( '#service_image' )[0].files[0] ); $.ajax({ url: someurl, // url where upload the image contentType: 'multipart/form-data', type: 'POST', data: datas, dataType: 'json', mimeType: 'multipart/form-data', success: function (data) { alert( data.url ); }, error : function (jqXHR, textStatus, errorThrown) { alert('ERRORS: ' + textStatus); }, cache: false, contentType: false, processData: false }); }); }); </script> <form id="myform" name="myform" method="post" enctype="multipart/form-data"> <input id="service_image" name="service_image" type="file" /> <input type=submit value="submit" /> </form> </body> </html>
PHP 내용
<?php $path = "./uploads/"; $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); $data = array(); $data['success'] = false; if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['service_image']['name']; $size = $_FILES['service_image']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size < ( 1024*1024 )) // Image size max 1 MB { $actual_image_name = time()."-image.".$ext; $tmp = $_FILES['service_image']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { $data['success'] = true; $data['url'] = "http://yoururl/uploads/".$actual_image_name; } else { $data['success'] = false; $data['error'] = "error"; } } else $data['error'] = "Image file size max 1 MB"; } else $data['error'] = "Invalid file format.."; } else $data['error'] = "Please select image..!"; } echo json_encode($data); ?>
Good Luck !
