使用CodeIgniter和Ajax在每个输入中上传多个文件 [英] Multiple file upload in each inputs using CodeIgniter and Ajax
问题描述
第二次输入后,我无法上传任何图像.我只能上传第一个输入.当添加另一个输入值时,将动态创建输入.下面是代码:
I am not able to upload any images after second input. I can only upload the first input. The inputs are created dynamically when another input value is added. Below is the code:
\\ jquery //
function storeupdate(){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>updatestore",
data:$("#mainstore").serialize(),
success: function(response){
var data = new FormData();
input = document.getElementById('file');
for(var i = 0; i < input.files.length; i++)
{
data.append('images[]', document.getElementById('file').files[i]);
}
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>storeupload',
cache: false,
contentType: false,
processData: false,
data : data,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
});
swal('Successful!', 'Data has been saved!', 'success');
//window.location.reload();
},
error: function() {
swal("Oops", "We couldn't connect to the server!", "error");
}
});
return false;
};
\\ view //
<input type="file" name="images[]" id="file" class="file" accept="image/*;capture=camera" multiple="multiple" />
<button type="button" class="btn btn-success save" id="save" name="save" onclick="storeupdate();" disabled>Save</button>
\\ controller //
public function storeupload()
{
$files= $_FILES;
$cpt = count ($_FILES['images']['name']);
for($i = 0; $i < $cpt; $i ++) {
$_FILES['images']['name'] = $files['images']['name'][$i];
$_FILES['images']['type'] = $files['images']['type'][$i];
$_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
$_FILES['images']['error'] = $files['images']['error'][$i];
$_FILES['images']['size'] = $files['images']['size'][$i];
$this->upload->initialize ( $this->set_upload_options1() );
$this->upload->do_upload("images");
$fileName = $_FILES['images']['name'];
$images[] = $fileName;
}
}
推荐答案
我制作并测试了一些代码示例,以便您可以了解问题所在.你有几件事错了.我建议的第一件事实际上是使用jQuery.您的代码显然使用的是jQuery,但是您有各种可以简化的普通JS:
I made and tested a little sample of code so that you can see what's wrong. You have a few things wrong. First thing I would recommend is actually using jQuery. Your code is obviously using jQuery, but you have all kinds of vanilla JS that can be simplified:
$(document).ready(function(){
$('#save').on('click', function(){
var fileInput = $('#file_input')[0];
if( fileInput.files.length > 0 ){
var formData = new FormData();
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
$.ajax({
method: 'post',
url:"/multi_uploader/process",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
}else{
console.log('No Files Selected');
}
});
});
请注意,我在ajax URL中进行了硬编码.我用于测试的控制器名为Multi_uploader.php.
Notice that I hard coded in the ajax URL. The controller I used for testing was named Multi_uploader.php.
接下来是在控制器中,当您遍历$ _FILES时,需要将其转换为"userfile".如果您打算使用CodeIgniter上传类,这是非常重要的:
Next is that in your controller when you loop through the $_FILES, you need to convert that over to "userfile". This is very important if you plan to use the CodeIgniter upload class:
public function process()
{
$F = array();
$count_uploaded_files = count( $_FILES['images']['name'] );
$files = $_FILES;
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES['userfile'] = [
'name' => $files['images']['name'][$i],
'type' => $files['images']['type'][$i],
'tmp_name' => $files['images']['tmp_name'][$i],
'error' => $files['images']['error'][$i],
'size' => $files['images']['size'][$i]
];
$F[] = $_FILES['userfile'];
// Here is where you do your CodeIgniter upload ...
}
echo json_encode($F);
}
这是我用于测试的视图:
This is the view that I used for testing:
<!doctype html>
<html>
<head>
<title>Multi Uploader</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/js/multi_uploader.js"></script>
</head>
<body>
<form>
<input type="file" name="images[]" id="file_input" multiple />
<button type="button" id="save">Upload</button>
</form>
</body>
</html>
最后,只是为了证明文件已上传到控制器,并且可以将它们与CodeIgniter一起使用,我将ajax响应作为json编码的数组发送,并在控制台中显示.请参阅代码注释,您可以在其中放置CodeIgniter上传代码.
Finally, just to prove that the files were uploaded to the controller, and that I could use them with CodeIgniter, I send the ajax response as a json encoded array, and display it in the console. See the code comment where you would put your CodeIgniter upload code.
如果您想输入多个文件,那么显然会稍微改变您的HTML和JS.在这种情况下,您的HTML将具有多个输入:
If you want to have multiple file inputs, then that obviously changes your HTML and JS a bit. In that case, your HTML would have the multiple inputs:
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
您的javascript需要更改以遍历每个输入:
And your javascript needs to change to loop through each input:
$(document).ready(function(){
$('#save').on('click', function(){
var fileInputs = $('.file_input');
var formData = new FormData();
$.each(fileInputs, function(i,fileInput){
if( fileInput.files.length > 0 ){
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
}
});
$.ajax({
method: 'post',
url:"/multi_uploader/process",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
});
有关将详细信息添加到数据库中的评论的更多信息---
使用CodeIgniter进行上传时,会提供以下上传摘要:
A little more info about your comment regarding adding the details to your database ---
When you do an upload with CodeIgniter, there is a provided upload summary:
$summary = $this->upload->data();
这是一组数据,最终看起来像这样:
This is an array of data that ends up looking like this:
$summary = array(
'file_name' => 'mypic.jpg',
'file_type' => 'image/jpeg',
'file_path' => '/path/to/your/upload/',
'full_path' => '/path/to/your/upload/jpg.jpg',
'raw_name' => 'mypic',
'orig_name' => 'mypic.jpg',
'client_name' => 'mypic.jpg',
'file_ext' => '.jpg',
'file_size' => 22.2
'is_image' => 1
'image_width' => 800
'image_height' => 600
'image_type' => 'jpeg',
'image_size_str' => 'width="800" height="200"'
);
因此,每次上传后,向数据库添加记录所需要做的就是这样:
So all you would have to do to add a record to your database is this after each upload:
$summary = $this->upload->data();
$this->db->insert('storefiles', array(
'Store_ID' => $_POST['storeid'],
'File_Name' => $summary['file_name'],
'Created' => date('Y-m-d h:i:s'),
'Modified' => date('Y-m-d h:i:s')
));
很容易看出,除了文件名之外,您还可以存储更多的内容.
It's pretty easy to see that you could store a lot more than just the filename.
这篇关于使用CodeIgniter和Ajax在每个输入中上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!