php - multiple - upload file codeigniter
ValidaciĆ³n de carga de archivos en Codeigniter (7)
No está obteniendo un error al usar la clase de carga de CI porque no está llamando a un error. Cambie su código de actualización 2 como se muestra a continuación
public function Task()
{
if ($this->form_validation->run(''Sub_Admin/task'') == FALSE) {
$this->data[''Task''] = $this->bm->get_usr();
$data[''title''] = "Add New Task";
$this->load->view(''Subadmin/header'',$data);
$this->load->view(''Subadmin/nav'');
$this->load->view(''Subadmin/sidebar'');
$this->load->view(''Subadmin/task'', $this->data);
$this->load->view(''Subadmin/footer'');
}
else
{
$config[''upload_path''] = ''./taskimages/''; //The path where the image will be save
$config[''allowed_types''] = ''gif|jpg|png''; //Images extensions accepted
$config[''max_size''] =''10048''; //The max size of the image in kb''s
//$config[''max_width''] = ''1024''; //The max of the images width in px
//$config[''max_height''] = ''768''; //The max of the images height in px
$config[''overwrite''] = FALSE; //If exists an image with the same name it will overwrite. Set to false if don''t want to overwrite
$this->load->library(''upload'', $config); //Load the upload CI library
$this->load->initialize($config);
if ( ! $this->upload->do_upload(''task''))
{
$upload_error = $this->upload->display_errors(); //Here you will get errors. You can handle with your own way
echo $upload_error; //<------------you can echo it for debugging purpose
$data[''error''] = $upload_error; //<-------------you can send it in view to display error in view.
$this->load->view(''your_view'' ,$data); //<---pass data to view
}
else
{
$file_info = $this->upload->data();
$file_name = $file_info[''file_name''];
$data = array(
''Job_Title'' => $this->input->post(''jtitle''),
''Priority'' => $this->input->post(''jnature''),
''Assignee'' => $this->input->post(''assigne''),
''Employee_Name'' => $this->input->post(''assignto''),
''Due_Date'' => $this->input->post(''ddate''),
''Reminder'' => $this->input->post(''reminder''),
''Task_Image'' => $file_name,
);
$this->bm->add_task($data);
}
}
}
En vista
echo (isset($error))?$error:"";
Estoy intentando validar la carga de archivos para la carga de imágenes, pero no está obteniendo la validación como en otros campos. Estoy usando el proceso Form_Validation.php
para la validación.
Array de carga de imágenes:
array(
''field''=>''image'',
''label'' => ''Image'',
''rules'' => ''required''
)
cuando intento cargar la imagen, no responde como se requiere, etc. También quiero validarla para .jpg
etc. y "cómo establecer el valor del archivo en un archivo incorrecto, como en lugar de .jpg
, intentamos cargar el .pdf
"como establecemos el valor del campo de entrada set_value(''field name'')
etc.
Revisé muchas preguntas y también intenté usar el método de llamada, pero no pude solucionarlo.
ACTUALIZAR:
Proporcione una respuesta detallada con un ejemplo de código. Utilice la forma form_validation.php en el ejemplo y también proporcione el código de ejemplo de devolución de llamada, para que pueda leer / aprender y modificarlo en consecuencia.
ACTUALIZACIÓN 2:
public function Task()
{
if ($this->form_validation->run(''Sub_Admin/task'') == FALSE) {
$this->data[''Task''] = $this->bm->get_usr();
$data[''title''] = "Add New Task";
$this->load->view(''Subadmin/header'',$data);
$this->load->view(''Subadmin/nav'');
$this->load->view(''Subadmin/sidebar'');
$this->load->view(''Subadmin/task'', $this->data);
$this->load->view(''Subadmin/footer'');
}
else
{
$config[''upload_path''] = ''./taskimages/''; //The path where the image will be save
$config[''allowed_types''] = ''gif|jpg|png''; //Images extensions accepted
$config[''max_size''] =''10048''; //The max size of the image in kb''s
//$config[''max_width''] = ''1024''; //The max of the images width in px
//$config[''max_height''] = ''768''; //The max of the images height in px
$config[''overwrite''] = FALSE; //If exists an image with the same name it will overwrite. Set to false if don''t want to overwrite
$this->load->library(''upload'', $config); //Load the upload CI library
$this->load->initialize($config);
$this->upload->do_upload(''task'');
$file_info = $this->upload->data();
$file_name = $file_info[''file_name''];
$data = array(
''Job_Title'' => $this->input->post(''jtitle''),
''Priority'' => $this->input->post(''jnature''),
''Assignee'' => $this->input->post(''assigne''),
''Employee_Name'' => $this->input->post(''assignto''),
''Due_Date'' => $this->input->post(''ddate''),
''Reminder'' => $this->input->post(''reminder''),
''Task_Image'' => $file_name,
);
$this->bm->add_task($data);
}
}
Ya estoy usando la clase de carga de CI, pero no está funcionando, y ahora quiero validar la imagen / archivo del lado de form_validation.
¿Qué hay de File Uploading Class de CI?
Las validaciones también están disponibles en la clase:
$config[''allowed_types''] = ''gif|jpg|png'';
$config[''max_size''] = 100;
$config[''max_width''] = 1024;
$config[''max_height''] = 768;
El enlace incluye el formulario de carga, la página de éxito y el controlador.
Solo sigue las instrucciones desde allí y nunca te perderás.
Actualmente no obtiene el error porque establece las reglas de validación, también ha inicializado la configuración, pero después de cargar la clase no está verificando si el archivo se está cargando o si hay errores.
Por favor, consulte la solución mencionada a continuación, que le ayudará a solucionar esto.
Actualización 1:
Para llamar a un grupo específico, pasará su nombre al método $this->form_validation->run(''task'')
. No puedo ver ninguna matriz $config[''task'']
en tu código. Por favor, compruebe mi código mencionado a continuación y actualice según sus inputs
.
public function Task() {
$config = array(
''task'' => array(
array(
''field'' => ''username'',
''label'' => ''Username'',
''rules'' => ''required''
),
array(
''field'' => ''email'',
''label'' => ''Email'',
''rules'' => ''required''
)
));
$this->load->library(''form_validation'');
if ($this->form_validation->run(''task'') == FALSE) {
$this->data[''Task''] = $this->bm->get_usr();
$data[''title''] = "Add New Task";
$this->load->view(''Subadmin/header'', $data);
$this->load->view(''Subadmin/nav'');
$this->load->view(''Subadmin/sidebar'');
$this->load->view(''Subadmin/task'', $this->data);
$this->load->view(''Subadmin/footer'');
} else {
$fconfig[''upload_path''] = ''./taskimages/'';
$fconfig[''allowed_types''] = ''gif|jpg|png'';
$fconfig[''max_size''] = ''10048'';
$fconfig[''overwrite''] = FALSE;
$this->load->library(''upload'', $fconfig); //Load the upload CI library
$this->load->initialize($fconfig);
if (!$this->upload->do_upload(''my_image'')) {
$error = array(''error'' => $this->upload->display_errors());
$this->load->view(''form'' ,$error);
} else {
$file_info = $this->upload->data();
$file_name = $file_info[''my_image''];
$data = array(
''Job_Title'' => $this->input->post(''jtitle''),
''Priority'' => $this->input->post(''jnature''),
''Assignee'' => $this->input->post(''assigne''),
''Employee_Name'' => $this->input->post(''assignto''),
''Due_Date'' => $this->input->post(''ddate''),
''Reminder'' => $this->input->post(''reminder''),
''Task_Image'' => $file_name,
);
$this->bm->add_task($data);
$data[''upload_data''] = array(''upload_data'' => $this->upload->data());
$this->load->view(''YOUR_SUCCESS_VIEW PAGE'', $data);
}
}
}
Avísame si no funciona.
Aquí solo escribo carga de archivos de muestra. Cámbielo según su requisito. controlador / Files.php
<?php if ( ! defined(''BASEPATH'')) exit(''No direct script access allowed'');
class Files extends CI_Controller {
function __construct() {
parent::__construct();
}
public function upload(){
$data = array();
$this->load->library(''form_validation'');
$this->load->helper(''file'');
$this->form_validation->set_rules(''task'', '''', ''callback_file_check'');
if($this->form_validation->run() == true){
//upload configuration
$config[''upload_path''] = ''uploads/files/'';
$config[''allowed_types''] = ''gif|jpg|png|pdf'';
$config[''max_size''] = 1024;
$this->load->library(''upload'', $config);
//upload file to directory
if($this->upload->do_upload(''task'')){
//YOU CAN DO WHAT DO THE PROCESS
}else{
$data[''error_msg''] = $this->upload->display_errors();
}
}
//load the view
$this->load->view(''upload_view'', $data);
}
public function file_check($str){
$allowed_mime_type_arr = array(''application/pdf'',''image/gif'',''image/jpeg'',''image/pjpeg'',''image/png'',''image/x-png''); //HERE you CAN GIVE VALID FILE EXTENSION
$mime = get_mime_by_extension($_FILES[''task''][''name'']);
if(isset($_FILES[''task''][''name'']) && $_FILES[''task''][''name'']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message(''file_check'', ''Please select only pdf/gif/jpg/png file.'');
return false;
}
}else{
$this->form_validation->set_message(''file_check'', ''Please choose a file to upload.'');
return false;
}
}
}
?>
view / upload_view.php
<?php
if(!empty($success_msg)){
echo ''<p class="statusMsg">''.$success_msg.''</p>'';
}elseif(!empty($error_msg)){
echo ''<p class="statusMsg">''.$error_msg.''</p>'';
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo base_url(); ?>files/upload">
<p><input type="task" name="task"/></p>
<?php echo form_error(''task'',''<p class="help-block">'',''</p>''); ?>
<p><input type="submit" name="uploadFile" value="UPLOAD"/></p>
</form>
Estoy usando este código para cargar imágenes múltiples. Ahora prueba el siguiente código, espero que ayude.
public function __construct(){
parent::__construct();
$this->load->helper(''date'');
$this->load->helper(''url'');
$this->load->helper(''form'');
$this->load->helper(''html'');
$this->load->library(''form_validation'');
$this->load->library(''email'');
$this->form_validation->set_error_delimiters('''', '''');
$config[''allowed_types''] = ''jpeg|jpg|png|bmp'';
$this->load->library(''upload'', $config);
$this->load->library(''session'');
}
public function Task() {
if ($this->form_validation->run(''Sub_Admin/task'') == FALSE) {
$this->data[''Task''] = $this->bm->get_usr();
$data[''title''] = "Add New Task";
$this->load->view(''Subadmin/header'',$data);
$this->load->view(''Subadmin/nav'');
$this->load->view(''Subadmin/sidebar'');
$this->load->view(''Subadmin/task'', $this->data);
$this->load->view(''Subadmin/footer'');
} else {
$filesCount = count($_FILES[''file''][''name'']);
$result = '''';
if($filesCount > 0) {
$event_id = trim($this->input->post(''event_name''));
for($i = 0; $i < $filesCount; $i++) {
$_FILES[''gallery''][''name''] = $_FILES[''file''][''name''][$i];
$_FILES[''gallery''][''type''] = $_FILES[''file''][''type''][$i];
$_FILES[''gallery''][''tmp_name''] = $_FILES[''file''][''tmp_name''][$i];
$_FILES[''gallery''][''error''] = $_FILES[''file''][''error''][$i];
$_FILES[''gallery''][''size''] = $_FILES[''file''][''size''][$i];
$image = $_FILES[''gallery''][''name''];
$directoryPath = date(''Y/M/'');
$path_info = pathinfo($image);
//check file type valid or not
if(in_array($path_info[''extension''], array(''jpg'', ''jpeg'',''png'', ''gif'',''JPG'',''JPEG''))){
// Upload job picture
$random = time();
$config[''upload_path''] = ''./taskimages/'';
$config[''allowed_types''] = ''jpg|png|jpeg|bmp'';
$config[''file_name''] = $random;
$config[''encrypt_name''] = TRUE;
$config[''max_size''] = ''250000000'';
$config[''max_width''] = ''75000000'';
$config[''max_height''] = ''7500000'';
$this->load->library(''upload'', $config);
$this->upload->initialize($config);
ini_set(''upload_max_filesize'', ''10M'');
ini_set(''memory_limit'', ''-1'');
if ($this->upload->do_upload(''gallery'')) {
$imageArray = $this->upload->data();
$image_name = $imageArray[''raw_name''] . '''' . $imageArray[''file_ext'']; // Job Attachment
$config1[''image_library''] = ''gd2'';
$config1[''source_image''] = ''./taskimages/'' . $image_name;
$config1[''create_thumb''] = TRUE;
$config1[''maintain_ratio''] = TRUE;
$config1[''width''] = 620;
$config1[''height''] = 540;
$this->load->library(''image_lib'', $config);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
$file_name = $image_name_thumb = $imageArray[''raw_name''] . ''_thumb'' . $imageArray[''file_ext''];
$data = array(
''Job_Title'' => $this->input->post(''jtitle''),
''Priority'' => $this->input->post(''jnature''),
''Assignee'' => $this->input->post(''assigne''),
''Employee_Name'' => $this->input->post(''assignto''),
''Due_Date'' => $this->input->post(''ddate''),
''Reminder'' => $this->input->post(''reminder''),
''Task_Image'' => $file_name,
);
$this->bm->add_task($data);
}
}
}
}
}
}
Prueba esto
public function add_partner()
{
$config =[
''upload_path'' => ''./uploads_image'',
''allowed_types'' => ''jpg|gif|png|jpeg'',//Image allowed Type
];
$this->load->library(''upload'',$config);//load image liabrary
$post=$this->input->post();
if($this->form_validation->run(''partner'') && $this->upload-
>do_upload(''userfile''))
{
$data = $this->upload->data();
$image_path = ("uploads_image/" .$data[''raw_name''] . $data[''file_ext'']);
$post[''partner_image''] = $image_path; //partner_image tabelfield name
unset($post[''submit'']);
$this->partner_model->add_partner($post);//data to model
}
else
{
$upload_error= $this->upload->display_errors();
$this->load->view(''admin/add_partner'',[''upload_error''=>$upload_error]);
}
}
In view
<div class="row">
<div class="col-lg-8">
<div class="form-group">
<label for="image" class="col-lg-5 control-label"> Upload Image<span style="color:red;">*</span></label>
<div class="col-lg-7"> <?php echo form_upload([''name''=>''userfile'',''class''=>''form-control'',''data-max-size''=>'' 2048'',''value''=>set_value(''userfile'')]); ?> </div>
</div>
</div>
<div class="col-lg-4"> <?php if(isset($upload_error)) echo $upload_error; ?> </div>
</div>
Escribí un ejemplo completo para su problema, espero que ayude. En el siguiente código, estoy utilizando la devolución de llamada de validación de formularios de CI y los mensajes de error personalizados de validación de formularios.
Controlador: Front.php
clase Front extiende CI_Controller {
public function index() {
$this->load->view(''form'');
}
public function upload_image() {
$this->load->library(''form_validation'');
if ($this->form_validation->run(''user_data'') == FALSE) {
$this->load->view(''form'');
}
else {
echo ''You form Submitted Successfully '';
}
}
public function validate_image() {
$check = TRUE;
if ((!isset($_FILES[''my_image''])) || $_FILES[''my_image''][''size''] == 0) {
$this->form_validation->set_message(''validate_image'', ''The {field} field is required'');
$check = FALSE;
}
else if (isset($_FILES[''my_image'']) && $_FILES[''my_image''][''size''] != 0) {
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "GIF", "PNG");
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$extension = pathinfo($_FILES["my_image"]["name"], PATHINFO_EXTENSION);
$detectedType = exif_imagetype($_FILES[''my_image''][''tmp_name'']);
$type = $_FILES[''my_image''][''type''];
if (!in_array($detectedType, $allowedTypes)) {
$this->form_validation->set_message(''validate_image'', ''Invalid Image Content!'');
$check = FALSE;
}
if(filesize($_FILES[''my_image''][''tmp_name'']) > 2000000) {
$this->form_validation->set_message(''validate_image'', ''The Image file size shoud not exceed 20MB!'');
$check = FALSE;
}
if(!in_array($extension, $allowedExts)) {
$this->form_validation->set_message(''validate_image'', "Invalid file extension {$extension}");
$check = FALSE;
}
}
return $check;
}
}
Vista: form.php
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h1><a href="<?= base_url() ?>">Form</a></h1>
<?php if(!empty(validation_errors())): ?>
<p><?= validation_errors() ?></p>
<?php endif; ?>
<?= form_open(''front/upload_image'', [''enctype'' => "multipart/form-data"]) ?>
<label>Name: </label><input type="text" name="name" value="<?= set_value(''name'') ?>"></label>
<label>E-mail: </label><input type="email" name="email" value="<?= set_value(''email'') ?>"></label>
<input type="file" name="my_image">
<button type="submit">Submit</button>
<?= form_close() ?>
</body>
</html>
form_validation.php
$config = array(
''user_data'' => array(
array(
''field'' => ''name'',
''label'' => ''Name'',
''rules'' => ''trim|required''
),
array(
''field'' => ''email'',
''label'' => ''Email'',
''rules'' => ''trim|required|valid_email''
),
array(
''field'' => ''my_image'',
''label'' => ''Image'',
''rules'' => ''callback_validate_image''
)
)
);
En el ejemplo anterior, primero estoy validando el name
y el email
y para la imagen estoy llamando a la función validate_image
para validarlo, ya que la biblioteca form_validation no proporciona validación de imagen pero tengo callbacks para hacer validaciones personalizadas, validate_image
verificará el tipo de contenido de la imagen y luego compruebe el tamaño del archivo de imagen y luego verifique la extensión de la imagen si alguno de estos requisitos no se cumple. Establecerá un mensaje de error para cada requisito utilizando la función set_message()
de la biblioteca form_validation
.