If you try and upload files with multi-dimensional names like this:
You will get an unexpected format like this:
array[
'submission' => array
[
'name' => array[ 'screenshot' => 'monster_wallpaper.jpg' ],
'type' => array[ 'screenshot' => 'image/jpeg' ],
'tmp_name' => array[ 'screenshot' => '/tmp/php48lX2Y' ],
'error' => array[ 'screenshot' => 0 ],
'size' => array[ 'screenshot' => 223262 ],
],
....
?>
You can use the following function to re-format the array recursively in the usual format:
________số 8
foreach[ $files as $key => &$part ]
{
$key = [ string ] $key;
if[ in_array[ $key, $names ] ]
$name = $key;
if[ !in_array[ $key, $names ] ]
$path[] = $key;
if[ is_array[ $part ] ]
$part = format_files_array[ $part, $name, $new, $path ];
elseif[ !is_array[ $part ] ]
{
$current =& $new;
foreach[ $path as $p ]
$current =& $current[$p];
$current[$name] = $part;
unset[ $path ];
$name = null;
}
}
defined['BASEPATH'] OR exit['No direct script access allowed'];0TẠO BẢNG `tệp` [ `id` int[11] NOT NULL AUTO_INCREMENT, `file_name` varchar[255] COLLATE utf8_unicode_ci NOT NULL, `uploaded_on` datetime NOT NULL, `status` enum['1','0'] COLLATEclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
Tải lên tệp là tính năng được sử dụng nhiều nhất trong ứng dụng web nơi các tệp được quản lý động. Có thể dễ dàng tải tệp lên máy chủ bằng PHP. Ngoài ra, bạn có thể tải lên nhiều tệp cùng một lúc bằng PHP. Đối với ứng dụng web CodeIgniter, bạn có thể sử dụng thư viện hệ thống để triển khai chức năng tải tệp lên. Thư viện CodeIgniter Upload giúp bạn upload file lên server trong CodeIgniter
Lớp Tải lên Tệp của CodeIgniter cho phép các tệp được tải lên máy chủ. Bạn có thể tải tệp hoặc hình ảnh lên dễ dàng bằng thư viện Tải lên trong CodeIgniter. Không chỉ một tệp mà còn có thể tải lên nhiều tệp bằng thư viện Tải lên CodeIgniter. Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách tải lên nhiều tệp và hình ảnh cùng lúc bằng Thư viện tải lên của CodeIgniter
Trong mã ví dụ, chức năng sau sẽ được triển khai để tải lên nhiều tệp trong CodeIgniter
- Tạo biểu mẫu HTML để chọn tệp hình ảnh để tải lên
- Tải nhiều hình ảnh lên máy chủ cùng lúc bằng thư viện Tải lên của CodeIgniter
- Lưu trữ dữ liệu tệp trong cơ sở dữ liệu MySQL
- Lấy hình ảnh từ cơ sở dữ liệu và hiển thị chúng trên trang web
Cách tải tệp lên trong CodeIgniter
Tạo bảng cơ sở dữ liệu
Để lưu trữ tên tệp và thông tin liên quan, cần có một bảng trong cơ sở dữ liệu. SQL sau đây tạo một bảng
defined['BASEPATH'] OR exit['No direct script access allowed'];1 với các trường cơ bản trong cơ sở dữ liệu MySQLclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
CREATE TABLE `files` [ `id` int[11] NOT NULL AUTO_INCREMENT, `file_name` varchar[255] COLLATE utf8_unicode_ci NOT NULL, `uploaded_on` datetime NOT NULL, `status` enum['1','0'] COLLATE utf8_unicode_ci NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Inactive', PRIMARY KEY [`id`] ] ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Tạo thư mục tải lên tệp
Tạo một thư mục trên máy chủ nơi bạn muốn lưu trữ các tệp đã tải lên. Ví dụ, tạo một thư mục
defined['BASEPATH'] OR exit['No direct script access allowed'];2 trong thư mục gốc của ứng dụng CodeIgniterclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
Bộ điều khiển [Upload_files. php]
Bộ điều khiển Upload_Files xử lý chức năng hiển thị hình ảnh và tải lên nhiều tệp
- __xây dựng[] -
- Tải mô hình tệp giúp chèn dữ liệu tệp vào cơ sở dữ liệu và lấy dữ liệu tệp từ cơ sở dữ liệu
- mục lục[] -
- Kiểm tra xem biểu mẫu tải lên có được gửi cùng với tệp không
- Đặt tùy chọn [đường dẫn tải lên, loại được phép, v.v.] và khởi tạo Thư viện tải lên
- Tải hình ảnh lên máy chủ bằng thư viện Tải lên
- Chèn dữ liệu hình ảnh vào cơ sở dữ liệu bằng phương pháp
defined['BASEPATH'] OR exit['No direct script access allowed'];
3 của mô hình Tệpclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
- Tìm nạp tất cả hình ảnh từ cơ sở dữ liệu bằng phương thức
defined['BASEPATH'] OR exit['No direct script access allowed'];
4 của mô hình Tệpclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
- Truyền dữ liệu hình ảnh và trạng thái tải lên cho chế độ xem
defined['BASEPATH'] OR exit['No direct script access allowed'];class Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
Mô hình [Tệp. php]
Mô hình Tệp xử lý các hoạt động liên quan đến cơ sở dữ liệu [tìm nạp và chèn]
- __construct[] – Xác định tên bảng nơi dữ liệu tệp sẽ được lưu trữ
- getRows[] –
- Lấy dữ liệu tệp từ cơ sở dữ liệu
- Trả về một bản ghi nếu ID được chỉ định, nếu không thì tất cả các bản ghi
- chèn[] -
- Chèn nhiều tệp dữ liệu vào cơ sở dữ liệu bằng cách sử dụng chức năng
defined['BASEPATH'] OR exit['No direct script access allowed'];
5 của CodeIgniter Query Builder Classclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
- Chèn nhiều tệp dữ liệu vào cơ sở dữ liệu bằng cách sử dụng chức năng
defined['BASEPATH'] OR exit['No direct script access allowed'];class File extends CI_Model{
function __construct[] {
$this->tableName = 'files';
}/*
* Fetch files data from the database
* @param id returns a single record if specified, otherwise all records
*/
public function getRows[$id = '']{
$this->db->select['id,file_name,uploaded_on'];
$this->db->from['files'];
if[$id]{
$this->db->where['id',$id];
$query = $this->db->get[];
$result = $query->row_array[];
}else{
$this->db->order_by['uploaded_on','desc'];
$query = $this->db->get[];
$result = $query->result_array[];
}
return !empty[$result]?$result:false;
}/*
* Insert file data into the database
* @param array the data for inserting into the table
*/
public function insert[$data = array[]]{
$insert = $this->db->insert_batch['files',$data];
return $insert?true:false;
}
}
Xem [upload_files/index. php]
Ban đầu, một biểu mẫu HTML được hiển thị với đầu vào tệp để chọn nhiều tệp
- Sau khi gửi biểu mẫu, dữ liệu được đăng lên chức năng
defined['BASEPATH'] OR exit['No direct script access allowed'];
6 của bộ điều khiển Upload_Files để tải nhiều hình ảnh lên máy chủclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
- Dựa trên phản hồi tải lên, thông báo trạng thái được hiển thị trên trang web
Trong biểu mẫu tải lên tệp,
- Tên tệp đã tải lên được tìm nạp từ cơ sở dữ liệu
- Các hình ảnh tương ứng được lấy từ máy chủ
- Các hình ảnh được liệt kê trong chế độ xem thư viện
Tải lên tùy chọn lớp học
Trong ví dụ này, một số tùy chọn cơ bản được sử dụng để Tải lên cấu hình thư viện [
defined['BASEPATH'] OR exit['No direct script access allowed'];7]. Nhưng bạn có thể chỉ định các tùy chọn khác nhau được cung cấp bởi Lớp tải lên trong CodeIgniterclass Upload_Files extends CI_Controller {
function __construct[] {
parent::__construct[];// Load file model
$this->load->model['file'];
}function index[]{
$data = array[];
$errorUploadType = $statusMsg = '';// If file upload form submitted
if[$this->input->post['fileSubmit']]{// If files are selected to upload
if[!empty[$_FILES['files']['name']] && count[array_filter[$_FILES['files']['name']]] > 0]{
$filesCount = count[$_FILES['files']['name']];
for[$i = 0; $i load->library['upload', $config];
$this->upload->initialize[$config];// Upload file to server
if[$this->upload->do_upload['file']]{
// Uploaded file data
$fileData = $this->upload->data[];
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date["Y-m-d H:i:s"];
}else{
$errorUploadType .= $_FILES['file']['name'].' | ';
}
}$errorUploadType = !empty[$errorUploadType]?'
File Type Error: '.trim[$errorUploadType, ' | ']:'';
if[!empty[$uploadData]]{
// Insert files data into the database
$insert = $this->file->insert[$uploadData];// Upload status message
$statusMsg = $insert?'Files uploaded successfully!'.$errorUploadType:'Some problem occurred, please try again.';
}else{
$statusMsg = "Sorry, there was an error uploading your file.".$errorUploadType;
}
}else{
$statusMsg = 'Please select image files to upload.';
}
}// Get files data from the database
$data['files'] = $this->file->getRows[];// Pass the files data to view
$data['statusMsg'] = $statusMsg;
$this->load->view['upload_files/index', $data];
}}
- upload_path – Đường dẫn của thư mục nơi tệp sẽ được tải lên. Đường dẫn phải tuyệt đối và thư mục phải ghi được
- allow_types – Loại mime của tệp cho phép tải lên
- file_name – Nếu được chỉ định, tệp đã tải lên sẽ được đổi tên bằng tên này
- file_ext_tolower – [TRUE/FALSE] Nếu được đặt thành TRUE, phần mở rộng tệp sẽ là chữ thường
- ghi đè – [TRUE/FALSE] TRUE – Nếu một tệp tồn tại có cùng tên, nó sẽ bị ghi đè. FALSE – Nếu một tệp tồn tại có cùng tên, một số sẽ được thêm vào tên tệp
- max_size – [tính bằng kilobyte] Kích thước tối đa của tệp được phép tải lên. Đặt thành 0 không giới hạn
- max_width – [tính bằng pixel] Chiều rộng tối đa của hình ảnh được phép tải lên. Đặt thành 0 không giới hạn
- max_height – [tính bằng pixel] Chiều cao tối đa của hình ảnh được phép tải lên. Đặt thành 0 không giới hạn
- min_width – [tính bằng pixel] Chiều rộng tối thiểu của hình ảnh được phép tải lên. Đặt thành 0 không giới hạn
- min_height – [tính bằng pixel] Chiều cao tối thiểu của hình ảnh được phép tải lên. Đặt thành 0 không giới hạn
- max_filename – Độ dài tối đa của tên tệp. Đặt thành 0 không giới hạn
Tải lên nhiều hình ảnh với Xem, Chỉnh sửa và Xóa trong CodeIgniter
Bạn có muốn nhận trợ giúp triển khai hay sửa đổi hoặc nâng cao chức năng của tập lệnh này không?