Загрузка файла в CodeIgniter PHP с использованием Ajax и jQuery

Я пытаюсь отправить / загрузить значение из ввода типа файла вместе с данными из текстового ввода в мою функцию do_upload () в CodeIgniter.

Я изучал здесь и на других веб-сайтах, как это сделать, и применил мои коды, но пока безуспешно, это все равно не сработает. Я не хочу использовать FormData, так как я не хочу добавлять <form> элемент на моей «форме».

Вот мой JQuery и Ajax:

$("#create_post").click(function(e){
var post_title = document.getElementById("post_title").value;
var post_image = document.getElementById("post_image").value;
var post_content = document.getElementById("post_content").value;
var post_labels = document.getElementById("post_labels").value;
if(post_title === "" && post_content === ""){
return;
}else{
$.ajax({
type: "post",
url: "./create/process_create",
enctype: 'multipart/form-data',
data: "post_title="+post_title+"&post_image="+post_image+"&post_content="+post_content+"&post_labels="+post_labels,
success: function(data){
$('#stage').hide();
var stage = document.getElementById('stage');
stage.innerHTML = data;
$('#stage').show(500);
}
});
}
});

Мой обработчик CodeIgniter:

public function process_create(){
$file = $this->input->post('post_image');
if(!empty($file)){
$image_name = $this->input->post('post_title').'_'.$this->main_model->get_unique_number();

$result = $this->do_upload($image_name);

if($result['result'] == 'success'){
$image_name = $result['file_name'];
$url = $this->main_model->create($image_name);
if($url){
redirect('/'.$url);
}
}
}else{
echo 'Empty.';
$url = $this->main_model->create();
if($url){
redirect('/'.$url);
}
}

return FALSE;
}

public function do_upload($file_name){
$config['upload_path'] = './images/uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png|JPEG|JPG|PNG';
$config['file_name'] = $file_name;
$config['max_size'] = '500';
$config['max_width'] = '500';
$config['max_height'] = '500';

$this->load->library('upload', $config);

if(!$this->upload->do_upload('post_image')){
//if the upload has failed
$title = 'Image Upload Error';
$error = array('error' => $this->upload->display_errors());

$this->load->view('error', $error);

$result['result'] = 'failed';

return $result;
}else{
//if the upload was successful
$image_data = $this->upload->data();
$image_name = $image_data['file_name'];

$result['file_name'] = $image_name;
$result['result'] = 'success';
echo 'Success';
return $result;
}
}

Мой HTML:

<div class='form-group'>
<label for='post_title'>Title:</label>
<input type='text' class='form-control' name='post_title' id='post_title' placeholder='Type title here...'>
</div>
<div class='form-group'>
<label for='post_image'>Select photo:</label>
<input type='file' name='post_image' id='post_image'>
</div>
<div class='form-group'>
<label for='post_content'>Content:</label>
<textarea class='form-control' name='post_content' id='post_content' placeholder='Type content here...'></textarea>
</div>
<div class='form-group'>
<label for='post_labels'>Labels:</label>
<input type='text' class='form-control' name='post_labels' id='post_labels' placeholder='Type label/ labels here, separate labels by comma...'>
</div>
<div class='form-group'>
<button class='btn btn-success' type='button' id='create_post'>Submit</button>
</div>

CodeIgniter validation_errors () возвращает следующее: «Вы не выбрали файл для загрузки».
Я работаю над этим в течение двух дней, пожалуйста, помогите.

0

Решение

Вы можете использовать FormData без элемента формы:

var data = new FormData();
// append your file
data.append('file', $('#post_image').files[0]);
/*
data.append(...
*/
jQuery.ajax({
url: './create/process_create',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
// action on success
});
0

Другие решения

Других решений пока нет …