Как да качите изображение и файл в CodeЗапалител (с пример)
⚡ Умно обобщение
CodeIgniter File Upload uses the built-in Upload library to move images and documents from an HTML form to a server directory. This example builds an upload form, a controller that validates type and size, and a results page confirming the upload.

CodeКачване на файл на Igniter
Управлението на файлове е от съществено значение за повечето уеб приложения. Ако сте разработчикping a content management system, then you will need to be able to upload images, word documents, PDF reports, and more. If you are working on a membership site, you may need to make provision for people to upload their profile images. The CodeIgniter File Uploading class makes it easy for us to do all of the above.
В този урок ще разгледаме как да използвате библиотеката за качване на файлове за зареждане на файлове.
Качване на изображения в Codeподпалвач
Качване на файл в Codeподпалвач has two main parts: the frontend and the backend. The frontend is handled by the HTML form that uses the form input type file. On the backend, the file upload library processes the submitted input from the form and writes it to the upload directory.
Let us begin with the input form.
Create a new directory called files in the application/views directory.
Добавете следните файлове в приложение/изгледи/файлове
- upload_form.php – този изглед съдържа HTML формата, която има входен тип файл и изпраща избрания файл на сървъра за обработка
- upload_result.php – this view displays the results of the uploaded image, including a link that we can click to view the results.
Добавете следния код към upload_form.php
<!DOCTYPE html> <html> <head> <title>CodeIgniter Image Upload</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div> <h3>Select an image from your computer and upload it to the cloud</h3> <?php if (isset($error)){ echo $error; } ?> <form method="post" action="<?=base_url(0)?>" enctype="multipart/form-data"> <input type="file" id="profile_image" name="profile_image" size="33" /> <input type="submit" value="Upload Image" /> </form> </div> </body> </html>
ТУК,
- if (isset($error)){…} checks if the error variable has been set. If the result is true, then the error returned by the upload library is displayed to the user.
- <input type=”file” id=”profile_image” name=”profile_image” size=”33″ /> the type file allows the user to browse to their computer and select a file for uploading.
Add the following code to upload_result.php
<!DOCTYPE html> <html> <head> <title>Image Upload Results</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div> <h3>Congratulations, the image has successfully been uploaded</h3> <p>Click here to view the image you just uploaded <?=anchor('images/'.$image_metadata['file_name'], 'View My Image!')?> </p> <p> <?php echo anchor('upload-image', 'Go back to Image Upload'); ?> </p> </div> </body> </html>
ТУК,
- <?=anchor(‘images/’.$image_metadata[‘file_name’], ‘View My Image!’)?> uses the anchor helper to create a link to the newly uploaded file in the images directory. The name is retrieved from the image metadata that is passed to the view when the file has successfully been uploaded.
Let us now create the controller that will respond to our image uploading.
Добавете нов файл ImageUploadController.php в приложение/контролери
Добавете следния код към ImageUploadController.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class ImageUploadController extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('url', 'form'); } public function index() { $this->load->view('files/upload_form'); } public function store() { $config['upload_path'] = './images/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = 2000; $config['max_width'] = 1500; $config['max_height'] = 1500; $this->load->library('upload', $config); if (!$this->upload->do_upload('profile_image')) { $error = array('error' => $this->upload->display_errors()); $this->load->view('files/upload_form', $error); } else { $data = array('image_metadata' => $this->upload->data()); $this->load->view('files/upload_result', $data); } } }
ТУК,
- клас ImageUploadController разширява CI_Controller {…} дефинира нашия клас контролер и разширява базовия контролер CI_Controller
- публична функция __construct() {…} инициализира метода на родителския конструктор и зарежда помощните адреси и формуляри
- публична функция index() {…} дефинира метода на индексиране, който се използва за показване на формата за качване на изображение
- public function store() {…} дефинира метода, който ще качи изображението и ще го съхрани на сървъра за уеб приложения.
- $config['upload_path'] = './images/'; задава директорията, в която да се качват изображенията
- $config[‘allowed_types’] = ‘gif|jpg|png’; defines the acceptable file extensions. This is important for security reasons. The allowed types ensure that only images are uploaded and other file types such as PHP cannot be uploaded, because they have the potential to compromise the server.
- $config[‘max_size’] = 2000; sets the maximum file size in kilobytes. In our example, the maximum file that can be uploaded is 2,000kb, close to 2MB. If the user tries to upload a file larger than 2,000kb, then the image will fail to upload and the library will return an error message.
- $config[‘max_width’] = 1500; sets the maximum width of the image, which in our case is 1,500 px. Any width larger than that results in an error.
- $config['max_height'] = 1500; определя максимално допустимата височина.
- $this->load->library('качване', $config); зарежда библиотеката за качване и я инициализира с масива $config, който дефинирахме по-горе.
- if (!$this->upload->do_upload(‘profile_image’)) {…} attempts to upload the submitted image, which in our case is named profile_image
- $error = array('error' => $this->upload->display_errors()); задава съобщението за грешка, ако качването е неуспешно
- $this->load->view('files/upload_form', $error); зарежда формуляра за качване на файл и показва съобщението за грешка, което се връща от библиотеката за качване
- $data = array('image_metadata' => $this->upload->data()); задава метаданните на изображението, ако качването е било успешно
- $this->load->view('files/upload_result', $data); зарежда успешно качения изглед и предава метаданните на качения файл.
That is it for the controller. Let us now create the directory where our images will be uploaded to. Create a new directory “images” in the root directory of your application.
Finally, we will add two routes to our routes.php file that will display the form and display the results.
Open application/config/routes.php and add the following routes
$route['upload-image'] = 'imageuploadcontroller'; $route['store-image'] = 'imageuploadcontroller/store';
ТУК,
- $route['upload-image'] = 'imageuploadcontroller'; дефинира URL качване на изображение, което извиква метода index на ImageUploadController
- $route['store-image'] = 'imageuploadcontroller/store'; дефинира URL store-image, който приема избрания потребителски файл и го качва на сървъра.
Как да поправим Common CodeIgniter File Upload Errors
Most upload failures return a clear message from the Upload library. The list below maps the common errors to their fixes.
- The filetype you are attempting to upload is not allowed: add the missing extension to the allowed_types config, for example ‘gif|jpg|png|pdf’.
- The file you are attempting to upload is larger than the permitted size: raise max_size, and confirm upload_max_filesize and post_max_size in php.ini are large enough.
- The upload path does not appear to be valid: create the upload_path directory and make sure the web server has write permission on it.
- You did not select a file to upload: check that the input name matches the do_upload() argument and that the form uses enctype multipart/form-data.
Тестване на приложението
Let us start the built-in PHP server.
Open the terminal or command line and browse to the root of your application. In my case, the root is located in drive C:\Sites\ci-app
cd C:\Sites\ci-app
Start the server using the following command
php -S localhost:3000
Заредете следното URL във вашия уеб браузър: http://localhost:3000/upload-image
You will be able to see the following results
Кликнете върху избор на файл
Трябва да можете да видите диалогов прозорец, подобен на следния
Select your desired image, then click on open
The selected file name will show up in the form upload as shown in the image above. Click on the Upload Image button.
You will get the following results, assuming everything goes well.
Click on the View My Image! link
You should be able to see the image that you uploaded. The results will be similar to the following.
Notice the uploaded image name is displayed in the URL. We got the image name from the uploaded image metadata.
Note: The file upload process remains the same for other types of files.





