php 在 CodeIgniter 中上传多个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8377218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload multiple files in CodeIgniter
提问by cycero
In my CodeIgniter project I'm uploading files during the project creation. Here's the uploading function:
在我的 CodeIgniter 项目中,我在项目创建期间上传文件。这是上传功能:
function uploadFiles(){
$this->load->library('upload');
$error = 0;
$projectName = $_POST['projectname'];
mkdir('./uploads/'.$projectName);
for($i=0; $i<count($_FILES); $i++)
{
$_FILES['userfile']['name'] = $_FILES['files']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['files']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['files']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['files']['size'][$i];
$config['upload_path'] = './uploads/'.$projectName;
$config['allowed_types'] = 'xml|etl';
$config['max_size'] = '0';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if($this->upload->do_upload())
{
$error += 0;
}else{
$error += 1;
}
}
if($error > 0){ return FALSE; }else{ return TRUE; }
}
And I call this function in the create_project function like this:
我在 create_project 函数中调用这个函数,如下所示:
public function create_project() {
$this->load->library('form_validation');
$this->form_validation->set_rules('projectname', 'Project name', 'required');
$this->form_validation->set_message('required', 'This is an obligatory field');
if($this->form_validation->run() == FALSE) {
$this->load->view('project_creation_view');
} else {
$this->load->model('Project_management_model');
$this->Project_management_model->create_project();
$this->uploadFiles();
}
}
However this does not do anything. The files are not being uploaded. Even an empty directory is not being created. Could anybody help me to find the error?
然而,这没有任何作用。未上传文件。甚至没有创建空目录。有人可以帮我找出错误吗?
Thanks.
谢谢。
回答by srbhbarot
You can Upload any number of Files..
您可以上传任意数量的文件..
$config['upload_path'] = 'upload/Main_category_product/';
$path=$config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload', $config);
foreach ($_FILES as $fieldname => $fileObject) //fieldname is the form field name
{
if (!empty($fileObject['name']))
{
$this->upload->initialize($config);
if (!$this->upload->do_upload($fieldname))
{
$errors = $this->upload->display_errors();
flashMsg($errors);
}
else
{
// Code After Files Upload Success GOES HERE
}
}
}
回答by Cubed Eye
This is an extension of the CI_Upload class that I modified to upload multiple files, just copy this to the MY_Upload.php file. It also makes the directory as well.
这是 CI_Upload 类的扩展,我修改后上传多个文件,只需将其复制到 MY_Upload.php 文件即可。它也使目录。
Then all you need to do in the controller function is arrange your files into the an array, where the name of the field and the key are the array keys and the config is the data. In you case something like this:
然后你需要在控制器函数中做的就是将你的文件排列成一个数组,其中字段的名称和键是数组键,配置是数据。在你的情况下是这样的:
$project_files['files'][0] = array(
'upload_path' => './uploads/'.$projectName.'/',
'max_size' => 0,
'allowed_types' => 'xml|etl',
'overwrite' => TRUE,
'remove_spaces' => TRUE,
);
$project_files['files'][1] = array(
'upload_path' => './uploads/'.$projectName.'/',
'max_size' => 0,
'allowed_types' => 'xml|etl',
'overwrite' => TRUE,
'remove_spaces' => TRUE,
);
IF all the files configs are the same just make a for loop to set this up, it will also take 'named keys', ie. $project_files['files']['file_key']
.
如果所有文件配置都相同,只需创建一个 for 循环来设置它,它也将采用“命名键”,即。$project_files['files']['file_key']
.
then just call:
然后只需调用:
if($this->upload->upload_files($project_files)){/*all files uploaded successfully*/}
回答by Reasoned
I can't comment yet because of my reputation level but Zoom made a comment under the accepted answer about the $fieldname variable being an array which caused an error. I had the same issue with that answer and found out that it was because I had appended all my file input names on the form with [] which made php pick up the those inputs as an array variable. To resolve that issue just give each file input a unique name instead of making it a PHP array. After I did that, the issue went away for me and the accepted answer worked like a charm. Just thought I'd pass the info along for anyone else who stumbles across this issue.
由于我的声誉级别,我还不能发表评论,但 Zoom 在接受的答案下发表了评论,关于 $fieldname 变量是一个导致错误的数组。我对那个答案有同样的问题,并发现这是因为我在表单上附加了我所有的文件输入名称 [] 这使得 php 将这些输入作为数组变量拾取。要解决该问题,只需为每个文件输入一个唯一名称,而不是将其设为 PHP 数组。在我这样做之后,这个问题对我来说就消失了,接受的答案就像一个魅力。只是想我会把信息传递给任何偶然发现这个问题的人。
回答by coderp
I modified Cubed Eye's MY_upload to return the file information of all files uploaded. As it was, only the last file's information was accessible when calling the data method. I also added the IP address of the uploader to that list.
我修改了Cubed Eye的MY_upload,返回所有上传文件的文件信息。实际上,在调用 data 方法时只能访问最后一个文件的信息。我还将上传者的 IP 地址添加到该列表中。
It can be utilized by the following:
它可以通过以下方式使用:
$upload_files = $this->upload->upload_files($project_files);
if ($upload_files->status == true)
{
$fileInfo = $uploaded_files->file_info;
}
I realize this would be better off as an edit to Cubed Eye but this is my first post, I have no reputation.
我意识到作为 Cubed Eye 的编辑会更好,但这是我的第一篇文章,我没有声誉。
回答by Tharanga
For the simplicity,I've created this CI helper file.You can load it from config file & use anywhere in your project.It just take 3 patrameters
为简单起见,我创建了这个 CI 帮助文件。您可以从配置文件加载它并在项目中的任何地方使用。它只需要 3 个参数
@fileobject = name of HTML file object
@fileobject = HTML 文件对象的名称
@fileopath = file path that you want to upload
@fileopath = 要上传的文件路径
@filetypes = default *,ex- 'jpg|png|mp4|pdf'
@filetypes = 默认 *,ex- 'jpg|png|mp4|pdf'
function fileUploader($fileobject, $filepath = "uploads/", $filetypes = "*"){
// retrieve the number of images uploaded;
$number_of_files = sizeof($_FILES[$fileobject]['tmp_name']);
// considering that do_upload() accepts single files, we will have to do a small hack so that we can upload multiple files. For this we will have to keep the data of uploaded files in a variable, and redo the $_FILE.
$files = $_FILES[$fileobject];
$errors = array();
$file_arr = array();
$result = array();
// first make sure that there is no error in uploading the files
for ($k = 0; $k < $number_of_files; $k++) {
if ($_FILES[$fileobject]['error'][$k] != 0) $errors[$k][] = 'Couldn\'t upload file ' . $_FILES[$fileobject]['name'][$k];
}
if (sizeof($errors) == 0) {
// now, taking into account that there can be more than one file, for each file we will have to do the upload
// we first load the upload library
$CI =& get_instance();
$CI->load->library('upload'); // load library
// next we pass the upload path for the images
$config['upload_path'] = FCPATH . $filepath;
// also, we make sure we allow only certain type of images
$config['allowed_types'] = $filetypes;
//$config['max_size'] = (int)(ini_get('upload_max_filesize'));
$config['max_size'] = '10000';
$config['overwrite'] = FALSE;
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['uploadedimage']['name'] = $files['name'][$i];
$_FILES['uploadedimage']['type'] = $files['type'][$i];
$_FILES['uploadedimage']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['uploadedimage']['error'] = $files['error'][$i];
$_FILES['uploadedimage']['size'] = $files['size'][$i];
//now we initialize the upload library
$CI->upload->initialize($config);
// we retrieve the number of files that were uploaded
if ($CI->upload->do_upload('uploadedimage')) {
$imageup = $CI->upload->data();
// print_r($imageup["orig_name"]);die;
array_push($file_arr, $imageup["orig_name"]);
$result["response"] = "true";
$result["message"] = "Files uploaded successfully.";
$result["files"] = $file_arr;
} else {
$result["response"] = "false";
$result["message"][$i] = $CI->upload->display_errors();
}
}
} else {
$result["response"] = "false";
$result["message"] = $errors;
}
return $result;}
Tested & proven.
测试和证明。
回答by landons
Thought I saw this same exact question here before ;)
以为我之前在这里看到过同样的问题;)
Try outputting $this->upload->display_errors() where you're incrementing the $error variable. That will tell you exactly what went wrong. My money's on permissions...
尝试在增加 $error 变量的地方输出 $this->upload->display_errors() 。这会告诉你到底出了什么问题。我的钱是权限...
回答by Sudhir Bastakoti
I think you missed this:
我想你错过了这个:
$config['file_name'] = 'somename_'.$i; $config['upload_path'] = './uploads/'.$projectName; ...