Chào các bạn, hôm nay mình sẽ hướng dẫn các bạn sử dụng ajax khi chúng ta upload file trong CodeIgniter!
Để nắm rõ dc TUT này, các bạn phải có kiến thức cơ bản về Json nha ! Tham thảo jsontại :http://www.qhonline.info/forum/showt...highlight=json.
+++Ở đây, chúng ta sẽ nạp vào thư viện AjaxFileUpload. Các bạn có thể tải tại đây:http://www.phpletter.com/DOWNLOAD/.
->Các bước cb đã xong !giờ chúng ta bắt tay vào viết ứng dụng nào .
Để nắm rõ dc TUT này, các bạn phải có kiến thức cơ bản về Json nha ! Tham thảo jsontại :http://www.qhonline.info/forum/showt...highlight=json.
+++Ở đây, chúng ta sẽ nạp vào thư viện AjaxFileUpload. Các bạn có thể tải tại đây:http://www.phpletter.com/DOWNLOAD/.
->Các bước cb đã xong !giờ chúng ta bắt tay vào viết ứng dụng nào .
+Đầu tiên, chúng ta tạo 1 bảng cấu trúc như sau:
Mã:
CREATE TABLE `files` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`file_name` varchar(255) NOT NULL,
`title` varchar(100) NOT NULL
);
+Tiếp theo, chúng ta có cấu trúc thư mục code như sau:
- application/
--- controllers/
------ upload.php
--- models/
------ mupload.php
--- views/
------ upload_view.php
------ files.php
- public/
--- css/
----- style.css
--- js/
----- AjaxFileUpload.js
----- jquery.js
- upload/ ->thư mục chứa file chúng ta upload lên.
->Trong controller upload.php ta xử lý như sau:
- application/
--- controllers/
------ upload.php
--- models/
------ mupload.php
--- views/
------ upload_view.php
------ files.php
- public/
--- css/
----- style.css
--- js/
----- AjaxFileUpload.js
----- jquery.js
- upload/ ->thư mục chứa file chúng ta upload lên.
->Trong controller upload.php ta xử lý như sau:
PHP Code:
class Upload extends CI_Controller{
public function __construct(){ parent::__construct(); $this->load->helper(array("url","form"));
}
public function index(){ $this->load->view("upload_view");
} //hàm trả về các file đã upload dc lưu trong database public function files(){ $this->load->model("mupload"); $data['files'] = $this->mupload->get_all_files(); $this->load->view("files",$data);
}
//hàm xử lý việc upload file và xuất thông báo dưới dạng json public function upload_file(){ $status = ""; $msg = ""; $tit = $this->input->post("title");
if($tit == NULL){ $status = "error"; $msg = "Please enter your title";
}
if($status != "error"){ $config['upload_path'] = '.upload'; $config['allowed_types'] = 'gif|jpg|png|doc|txt'; $config['max_size'] = 1024 * 8; $config['encrypt_name'] = TRUE; $this->load->library("upload",$config);
if(!$this->upload->do_upload("ufile")){ $status = "error"; $msg = $this->upload->display_errors('<p>','</p>');
echo $msg;
}else{ $this->load->model("mupload"); $data = $this->upload->data(); $info = array("file_name" => $data['file_name'], "title" => $_POST['title']); $fid = $this->mupload->insert_file($info);
if($fid){ $status = "Success"; $msg = "File successfully uploaded";
}else{ $status = "error"; $msg = "File uploaded fail! PLease try again!";
}
}
}
Echo json_encode(array("status" => $status, "msg" => $msg));
}
//hàm xử lý xóa file upload public function delete_files($file_id){ $this->load->model("mupload");
if($this->mupload->delete_file($file_id)){ $status = 'success'; $msg = 'File successfully deleted';
}else{ $status = 'error'; $msg> = 'Something went wrong when deleting the file, please try again';
}
Echo json_encode(array('status' => $status, 'msg' => $msg));
}
}
->Đây là file model của chúng ta:
mupload.php:
mupload.php:
PHP Code:
classMupload extends CI_Model{
protected $_table = "files";
public function __construct(){ parent::__construct(); $this->load->database();
}
public function insert_file($data){ $this->db->insert($this->_table,$data);
return $this->db->insert_id();
}
public function get_all_files($file_id =""){
if($file_id != ""){ $this->db->where("id",$file_id);
}
return $this->db->get($this->_table)->result_array();
}
public function delete_file($file_id){ $file = $this->get_all_files($file_id);
if($file == ""){
return FALSE;
}else{ $this->db->where("id",$file_id); $this->db->delete($this->_table); unlink("./upload/" . $file[pan style="color:rgb(0,0,187);">0]['file_name']); //xóa file upload trong thư mục chứa return TRUE;
}
}
}
Và cuối cùng ta có 2 trang view:
upload_view.php:
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="<?php echo base_url();?>public/js/jquery.js"></script>
<script src="<?php echo base_url()?>public/js/ajaxfileupload.js"></script>
<link href="<?php echo base_url()?>public/css/style.css" rel="stylesheet" />
<script language="javascript">
refresh_files();//Show ra list cac file da upload
$(document).ready(function(){
//xu ly upload file
$("#submit").click(function(){
$.ajaxFileUpload({
url : "./upload/upload_file",
secureuri : false,
fileElementId : "ufile",
dataType :"json",
data : {"title" : $("#title").val() },
success : function(data, status){
if(data.status != "error"){
$("#files").html("<p>Loading....</p>");
refresh_files();
$("#title").val("");
}
alert(data.msg);
}
});
return false;
}); //ket thuc upload file
//Xu ly delete file upload
$(".delete_file_link").live("click",function(){
if(confirm("Do you want to delete this file?")){
varlink_url = $(this);
//var files = $("#files");
//alert(files);
//alert(link_url.data("file_id"));
$.ajax({
url : "./upload/delete_files/" + link_url.data("file_id"),
dataType : "json",
success : function(data){
files = $("#files");
if(data.status == "success"){
link_url.parents("li").fadeOut("fast", function(){
$(this).remove();
if(files.find('li').length == 0){
files.html('<p>No Files Uploaded</p>');
}
});
}else{
alert(data.msg);
}
}
})
}
})//ket thuc xu ly file upload
})
function refresh_files()
{
$.get('./upload/files/').success(function (data){
$('#files').html(data);
});
}
</script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload_file" enctype="multipart/form-data">
<label>Title</label>
<input type="text" name="title" id="title"/>
<label>File</label>
<input type="file" name="ufile" id="ufile" size="25" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
<h2>Files</h2>
<div id="files"></div>
</body>
</html>
và files.php
PHP Code:
<?php if(isset($files)){
echo "<ul>";
foreach($files as $items){
echo "<li class='image_wrap'>";
echo "<a href='' class='delete_file_link' data-file_id='$items[id]'>Delete</a>";
echo "<strong>$items[title]</strong><br />";
echo "<imgsrc='". base_url()."upload/$items[file_name]' width='150' />";
echo "</li>";
}
echo "</ul>";
}
else{
echo "<p>No Files Uploaded</p>";
} ?>
Trong đó upload _view.php sẽ là trang chúng ta dùng ajax để xử lý việc upload cũng như delete các file. Còn files.php sẽ là trang dùng để show ra các file chúng ta đã upload thành công.
-->files.php sẽ dc gọi để hiển thị trong upload_view.php qua function refresh_filestrong đoạn javascript.
-->files.php sẽ dc gọi để hiển thị trong upload_view.php qua function refresh_filestrong đoạn javascript.
No comments:
Post a Comment