Hôm nay sharecodeweb sẽ hướng dẫn các bạn thực hiện thủ thuật upload và chọn nhiều ảnh cùng lúc sử dụng Ajax và Jquery.
Giới thiệu
Nếu bạn nào đã từng sử dụng wordpress thì sẽ thấy cơ chế upload và select của phần media vào bài post ấy rất hay đúng không. Tư tưởng của bài viết này cũng giúp các bạn thực hiện được điều đó, giống như chúng ta sử dụng wordpress vậy.
Bài này cũng đã được sharecodeweb dịch từ 9lessions về cho các bạn học. Ngoài ra các bạn có thể tham khảo bài Multiple Ajax Image Upload mà không refesh lại trình duyệt.
Để dễ hình dung được chi tiết của bài viết này nhé.
Về cơ bản, khi người dùng nhấn nút Open, cửa sổ mở file sẽ hiển thị để người dùng lựa chọn. Sau khi chọn xong những bức ảnh cần upload, chương trình sử dụng PHP và jQuery để xử lý tiếp.
Database
Đầu tiên là phải tạo một cơ sở dữ liệu để chúng ta có thể khai thác nó cái đã. DB làm nhiệm vụ lưu lại đường dẫn ảnh và những thứ liên quan
Bảng User
1 2 3 4 5 6 | CREATE TABLE `users` ( `user_id` int(11) AUTO_INCREMENT PRIMARY KEY, `username` varchar(255) UNIQUE KEY, `password` varchar(100), `email` varchar(255) UNIQUE KEY ) |
Bảng User Upload
1 2 3 4 5 6 | CREATE TABLE `user_uploads` ( `upload_id` int(11) AUTO_INCREMENT PRIMARY KEY, `image_name` text, `user_id_fk` int(11), `created` int(11) ) |
Ajax
Nói tới cách sử dụng ajax thì tất nhiên phải có ajax rồi chứ nhỉ. Đoạn ajax của chúng ta như sau:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <script type="text/javascript" src="http://ajax.googleapis.com/ ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script type="text/javascript" src="jquery.wallform.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#photoimg').live('change', function(){ var A=$("#imageloadstatus"); var B=$("#imageloadbutton"); $("#imageform").ajaxForm({target: '#preview', beforeSubmit:function(){ A.show(); B.hide(); }, success:function(){ A.hide(); B.show(); }, error:function(){ A.hide(); B.show(); } }).submit(); }); }); </script> |
Đoạn ajax này rất đơn giản, chỉ xử lý sự kiện hiển thị/ẩn đi nút bấm upload và dòng trạng thái sau khi upload.
File Index.php
Tập tin này sẽ chứa một form, trong đó có một thẻ input
cho phép user upload file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php include('db.php'); session_start(); $session_id='1'; // User login session value ?> <div id='preview'> </div> <form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both"> Upload image: <div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div> <div id='imageloadbutton'> <input type="file" name="photos[]" id="photoimg" multiple="true" /> </div> </form> |
File Ajax.php
Tập tin này có hàm getExtension
dùng để lấy ra phần mở rộng của tập tin. Sau đó làm cơ sở để kiểm tra xem người dùng đã chọn đúng tập tin ảnh để upload hay không?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php error_reporting(0); session_start(); include('db.php'); $session_id='1'; //$session id define ("MAX_SIZE","2000"); // 2MB MAX file size function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // Valid image formats $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $uploaddir = "uploads/"; //Image upload directory foreach ($_FILES['photos']['name'] as $name => $value) { $filename = stripslashes($_FILES['photos']['name'][$name]); $size=filesize($_FILES['photos']['tmp_name'][$name]); //Convert extension into a lower case format $ext = getExtension($filename); $ext = strtolower($ext); //File extension check if(in_array($ext,$valid_formats)) { //File size check if ($size < (MAX_SIZE*1024)) { $image_name=time().$filename; echo "<img src='".$uploaddir.$image_name."' class='imgList'>"; $newname=$uploaddir.$image_name; //Moving file to uploads folder if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) { $time=time(); //Insert upload image files names into user_uploads table mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')"); }else{ echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; } }else{ echo '<span class="imgList">You have exceeded the size limit!</span>'; } }else{ echo '<span class="imgList">Unknown extension!</span>'; } } //foreach end } ?> |
Ngoài ra cũng cần có file db.php
kết nối tới cơ sở dữ liệu chứ nhỉ
1 2 3 4 5 6 7 8 9 | <?php $mysql_hostname = "localhost"; $mysql_user = "username"; $mysql_password = "password"; $mysql_database = "database"; $prefix = ""; $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong"); mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong"); ?> |
Cuối cùng là CSS
Css lại cho đẹp, một chút xíu thôi. ai cần đẹp hơn thì cố gắng thể hiện trình style của mình nhé. Hoặc có thể tham khảo thiết kế form upload không refesh lại trình duyệt để css cho đẹp.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #preview { color:#cc0000; font-size:12px } .imgList { max-height:150px; margin-left:5px; border:1px solid #dedede; padding:4px; float:left; } |
Download code upload nhiều ảnh cùng lúc
Ngoài ra các bạn cũng có thể download code bên dưới đây để học hỏi kỹ hơn nhé
[postbytag bytag=”upload-anh”]Upload ảnh bằng ajax[/postbytag]
You must log in to post a comment.