如何使用 Ajax 以一种形式 CI 上传包含数据的图像



>我创建了一个用于添加广告的表单,您可以在其中输入一些文本输入,并在它们下面添加一个添加照片的地方,如果只是添加照片而不重新加载页面 - 它有效,我只是选择照片并通过一个按钮发送整个表单,将照片上传到服务器,然后将照片名称添加到数据库中。但我希望这个表单更有用,并在发送整个表单之前预览这些照片,所以我添加了 Ajax 脚本。问题是,当您选择照片并将其上传到服务器时,我不知道如何将它们传输到主表单。

我尝试在上传功能的末尾添加$this->create($photos)并在创建函数中选取它们。我把它们传递出去,但是一旦Ajax在上传第一页时重新加载了第一页。当我填写表单的文本字段并按发送表单时,$ photos 为 NULL,我不知道如何将这些数据传输并保存在数据库中?你如何让它工作?

public function create()
{
if ( !empty( $_POST ) )
{
if ( $this->form_validation->run( 'site_ads_create' ) == true )
{
$activate_code = random_string();
if ( logged_in() == true ) 
{
$data = array(
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'subcat' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'email' => $this->session->userdata( 'email' ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 1,

);
}
else
{
$data = array(
'title' => $this->input->post( 'title' , true ),
'description' => $this->input->post( 'description' , true ),
'category_id' => $this->input->post( 'subcat' , true ),
'city_id' => $this->input->post( 'city_id' , true ),
'price' => $this->input->post( 'price' , true ),
'contact' => $this->input->post( 'contact' , true ),
'email' => $this->input->post( 'email' , true ),
'phone' => $this->input->post( 'phone' , true ),
'user_ip' => getUserIpAddr(),
'created' => time(),
'active' => 0,
'activate_code' => $activate_code,

);  
}
$add = $this->Site_model->create( 'ads' , $data );
$this->session->set_flashdata( 'alert' , 'Ogłoszenie zostało dodane.' );
//redirect( '/dodaj-ogloszenie' );
}
else
{
$this->session->set_flashdata( 'alert' , validation_errors() );
//refresh();
}
}
$data['cities'] = $this->Site_model->get_cities('cities', 'name', 'asc');
$data['categories'] = $this->Site_model->get_categories();
$this->load->view( 'create' , $data );
}

上传功能

public function upload()
{
if($_FILES["files"]["name"] != '')
{
$output = '';
$path = BASEPATH . '../images/'. date('y').'_'.date('m').'/';
if ( !file_exists( $path ) )
{
mkdir( $path , 0777 );
}
$config['upload_path'] = 'images/'. date('y').'_'.date('m').'/'; 
$config["allowed_types"] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
{
$_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
$output .= '
<div class="col-md-3">
<img src="'.base_url().'images/'. date('y').'_'.date('m').'/'.$data["file_name"].'" class="img-responsive img-thumbnail" />
</div>
';
$photos[] = $this->upload->data();
}
}
echo $output;   
}
}

以及带有 Ajax 脚本的一段表单

<form method='post' action='<?php echo base_url();?>ads/create' enctype='multipart/form-data'>
...
<div class="container">
<br /><br /><br />
<h3 align="center">Upload Multiple Files in Codeigniter using Ajax JQuery</h3><br />
<div class="col-md-6" align="right">
<label>Select Multiple Files</label>
</div>
<div class="col-md-6">
<input type="file" name="files" id="files" multiple />
</div>
<div style="clear:both"></div>
<br />
<br />
<div id="uploaded_images"></div>
</div>
<script>
$(document).ready(function(){
$('#files').change(function(){
var files = $('#files')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"<?php echo base_url(); ?>ads/upload", 
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
$('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data)
{
$('#uploaded_images').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
});
</script>
<?php echo form_close(); ?>

如果要在上传之前预览图像,请使用FileReader执行此操作。这是代码,

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
//imgInp is ID form upload file
$("#imgInp").change(function(){
readURL(this);
});

相关内容

  • 没有找到相关文章

最新更新