i'm try to build REST API use codeigniter plugin from https://github.com/chriskacerguis/codeigniter-restserver
i'm successfull built multiple upload with this, but i have a trouble when upload many file data.
when i'm select 3 file in my directory, my code work, but in upload path i just have 2 file.
here controller :
function upload_post()
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
{
for($s=0; $s<=$count-1; ) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = 'E:/tes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
$s++;
}
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
print_r($count);
}
I have made a helper function for me which upload the files and return a array with upload result.It takes a parameter upload directory where to save the files. Here is the my function
function upload_file($save_dir="images")//takes folder name where to save.default images folder
{
$CI = & get_instance();
$CI->load->library('upload');
$config=array();
$config['upload_path'] = FCPATH.$save_dir;
$config['allowed_types'] = 'gif|jpg|png';//only images.you can set more
$config['max_size'] = 1024*10;//10 mb you can increase more.Make sure your php.ini has congifured same or more value like this
$config['overwrite'] = false;//if file do not replace.create new file
$config['remove_spaces'] = true;//remove sapces from file
//you can set more config like height width for images
$uploaded_files=array();
foreach ($_FILES as $key => $value)
{
if(strlen($value['name'])>0)
{
$CI->upload->initialize($config);
if (!$CI->upload->do_upload($key))
{
$uploaded_files[$key]=array("status"=>false,"message"=>$value['name'].': '.$CI->upload->display_errors());
}
else
{
$uploaded_files[$key]=array("status"=>true,"info"=>$CI->upload->data());
}
}
}
return $uploaded_files;
}
Sample output
if you print out the function returns you will get the output like this
Array
(
[file_input_name1] => Array
(
[status] => 1//status will be true if uploaded
[info] => Array //if success it will return the file informattion
(
[file_name] => newfilename.jpg
[file_type] => image/jpeg
[file_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/
[full_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/newfilename.jpg
[raw_name] => newfilename
[orig_name] => newfilename.jpg
[client_name] => newfilename
[file_ext] => .jpg
[file_size] => 762.53
[is_image] => 1
[image_width] => 1024
[image_height] => 768
[image_type] => jpeg
[image_size_str] => width="1024" height="768"
)
)
[file_input_name_2] => Array
(
[status] =>//if invalid file status will be false with error message
[message] => desktop.ini: <p>The filetype you are attempting to upload is not allowed.</p>
)
)
Hope it may help you
Related
In my CodeIgniter project, I'm uploading multiple files during the project creation. Please let me know how to upload multiple file using CI.
This is output array after submit form.
[user_attached] => Array
(
[name] => Array
(
[pic_passport] => cp-user-error.png
[att_document] => local-delivery-done.png
)
[type] => Array
(
[pic_passport] => image/png
[att_document] => image/png
)
[tmp_name] => Array
(
[pic_passport] => C:\xampp\tmp\phpC707.tmp
[att_document] => C:\xampp\tmp\phpC718.tmp
)
[error] => Array
(
[pic_passport] => 0
[att_document] => 0
)
[size] => Array
(
[pic_passport] => 635392
[att_document] => 36512
)
)
To Upload Multiple File in Codeigniter. Try this.
$filesCount = count($_FILES['user_attached']['name']);
$path = 'upload/document';
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$array = ['pic_passport','att_document'];
for($i = 0; $i < $filesCount; $i++) {
$_FILES['userFile']['name'] = $_FILES['user_attached']['name'][$array[$i]];
$_FILES['userFile']['name'] = $_FILES['user_attached']['name'][$array[$i]];
$_FILES['userFile']['type'] = $_FILES['user_attached']['type'][$array[$i]];
$_FILES['userFile']['tmp_name'] = $_FILES['user_attached']['tmp_name'][$array[$i]];
$_FILES['userFile']['error'] = $_FILES['user_attached']['error'][$array[$i]];
$_FILES['userFile']['size'] = $_FILES['user_attached']['size'][$array[$i]];
$imagename = $this->randomAlphanumId(10);
$image_name[$array[$i]]="doc_".$imagename."_".str_replace(array(' '),'_',$_FILES['userFile']['name']);
$config['upload_path'] = $path;
$config['allowed_types'] = '*';
$config['file_name'] = $image_name[$array[$i]];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')) {
$fileData = $this->upload->data();
$upload_image[] = $fileData['file_name'];
}
}
Create library for this code and call from controller
for($i = 0; $i < $config_array['files_count']; $i++)
{
if($config_array['file_data']['name'][$i])
{
$file_name = $config_array['file_data']['name'][$i];
$file_info = pathinfo($file_name);
$new_file_name = preg_replace('/[[:space:]]+/', '_', $file_info['filename']);
$new_file_name = $new_file_name.'_'.DATE(UPLOAD_FILE_DATE_FORMAT);
$new_file_name = str_replace('.','_',$new_file_name);
$file_extension = $file_info['extension'];
$new_file_name = $new_file_name.'.'.$file_extension;
$_FILES['attchment']['name'] = $new_file_name;
$_FILES['attchment']['tmp_name'] = $config_array['file_data']['tmp_name'][$i];
$_FILES['attchment']['error'] = $config_array['file_data']['error'][$i];
$_FILES['attchment']['size'] = $config_array['file_data']['size'][$i];
$config['upload_path'] = $config_array['file_upload_path'];
$config['file_name'] = $new_file_name;
$config['allowed_types'] = $config_array['file_permission'];
$config['file_ext_tolower'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['max_size'] = $config_array['file_size'];
$this->CI->load->library('upload',$config);
$this->CI->upload->initialize($config);
if($this->CI->upload->do_upload('attchment'))
{
array_push($file_array,array(
'og_name'=> $file_name,
'name'=> $new_file_name)
);
}
else
{
array_push($error_msgs,$this->CI->upload->display_errors('',''));
}
}
}
How would I insert "_thumb" before file extension ?
for example 123.jpg into 123_thumb.jpg
please answer my question, it's been 3 days i didn't find the right way.. thank you
this is my view :
<div class="row service-box margin-bottom-40">
<!-- carousel -->
<div class="col-md-4">
<div class="carousel slide">
<?php
$reports_slide = $this->m_dashboard->report_slide();
foreach ($reports_slide as $row) {
echo '
<img width="100%" src="' . base_url() . 'img/report/thumbs/' . $row->report_img . '" class="mySlides">
';
} ?>
<script>
var slideIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}
</script>
</div>
</div>
and this is my controller :
public function add_report()
{
$field_img = "img";
$field_thumb = "thumb";
$field_pdf = "pdf";
// this is for form field 1 which is an image....
$config['upload_path'] = '../img/report/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = '1024';
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$this->load->view('includes/header');
$this->load->view('includes/menu');
if (isset($_POST['submit'])) {
if (isset($_FILES['img']['name']) && is_uploaded_file($_FILES['img']['tmp_name'])){
$config['file_name'] = '_image_'.$_POST['id_company'].'_'.$_POST['report_title'];
$this->upload->initialize($config);
$this->upload->do_upload($field_img);
$file_name = $this->upload->data();
$file_img = $file_name['file_name'];
$config = array(
'image_library' => 'gd2',
'source_image' => $file_name['full_path'],
'new_image' => '../img/report/thumbs/',
'create_thumb' => TRUE,
'maintain_ratio' => FALSE,
'width' => 827,
'height' => 1170,
);
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
}
}
}
and this is my Model :
public function report_slide()
{
//report
$this->db->select('a.*, b.category_name, c.co_abbreviated_name, d.country_name, e.language, f.report_type, g.year, h.type');
$this->db->from('rc_report a, rc_category b, rc_company c, rc_country d, rc_language e, rc_report_type f, rc_year g, rc_gri h');
$this->db->where('b.id_category = a.id_category');
$this->db->where('c.id_company = a.id_company');
$this->db->where('d.id_country = a.id_country');
$this->db->where('e.id_language = a.id_language');
$this->db->where('f.id_report_type = a.id_report_type');
$this->db->where('g.id_year = a.id_year');
$this->db->where('h.id_gri = a.id_gri');
$this->db->order_by('g.year','desc');
$this->db->limit(5);
$query_report = $this->db->get();
$result_array=$query_report->result();
return $result_array;
}
English is not my native language, sorry for that.
For set à new name for your thumb, you just change this config
'new_image' => '../img/report/thumbs/'
When you do this you get the lot of informations about file
$file_name = $this->upload->data();
If you like inside the Ci::Upload, you see the function data return this
public function data($index = NULL)
{
$data = array(
'file_name' => $this->file_name,
'file_type' => $this->file_type,
'file_path' => $this->upload_path,
'full_path' => $this->upload_path.$this->file_name,
'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)),
'orig_name' => $this->orig_name,
'client_name' => $this->client_name,
'file_ext' => $this->file_ext,
'file_size' => $this->file_size,
'is_image' => $this->is_image(),
'image_width' => $this->image_width,
'image_height' => $this->image_height,
'image_type' => $this->image_type,
'image_size_str' => $this->image_size_str,
);
if ( ! empty($index))
{
return isset($data[$index]) ? $data[$index] : NULL;
}
return $data;
}
In your case what interests you it's
'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)),
Which give :
$config = array(
'image_library' => 'gd2',
'source_image' => $file_name['full_path'],
'new_image' => "../img/report/thumbs/".$file_name['raw_name']."_thumb.".$file_name['file_ext'],
'create_thumb' => TRUE,
'maintain_ratio' => FALSE,
'width' => 827,
'height' => 1170,
);
PS: See this Codeigniter image resize() thumbnail name issue
i use this extension : http://www.matmoo.com/digital-dribble/codeigniter/image_moo/
It's more successful than Codeigniter's own library. Especially when I want to save thumbnails in multiple sizes.
I have images I want to save in different formats based on user selection using GD. For PNG, JPG, and GIF images, there is a function to save the image in that format.
How can I save the image as TIFF, BMP, or PSD? Is any function available for those formats?
You cannot do that with GD, you need to use ImageMagick. I assume you have already image in a format png, and that image url is $imageUrl.;
$imageFormat = $_POST["format"];
$imageFormats = array("tiff", "bmp");
if (in_array($imageFormat, $imageFormats)) {
$handle = fopen($imageUrl, 'rb');
$imageMagick = new Imagick();
$imageMagick->readImageFile($handle);
$imageMagick->setImageFormat($imageFormat);
$imageMagick->setImageColorSpace(5);
$imageMagick->writeImage("path_to_tiff_image." . $imageFormat);
fclose($handle);
$imageMagick->destroy();
} else {
die("Invalid format!");
}
For PSD part, why do you want to save it as psd? There is no way to do that. If you say the reason of saving as psd, I can help you.
You can use inbuilt image type and mime type of GD library. Ex:
array (IMAGETYPE_PSD => 'psd', "mime_type" => 'image/psd'),
array (IMAGETYPE_BMP => 'bmp', "mime_type" => 'image/bmp'),
array (IMAGETYPE_TIFF_II => 'tiff', "mime_type" => 'image/tiff')
<?php
if(!function_exists('image_type_to_extension')){
$extension;
function image_type_or_mime_type_to_extension($image_type, $include_dot) {
define ("INVALID_IMAGETYPE", '');
$extension = INVALID_IMAGETYPE; /// Default return value for invalid input
$image_type_identifiers = array ( ### These values correspond to the IMAGETYPE constants
array (IMAGETYPE_GIF => 'gif', "mime_type" => 'image/gif'), ### 1 = GIF
array (IMAGETYPE_JPEG => 'jpg', "mime_type" => 'image/jpeg'), ### 2 = JPG
array (IMAGETYPE_PNG => 'png', "mime_type" => 'image/png'), ### 3 = PNG
array (IMAGETYPE_SWF => 'swf', "mime_type" => 'application/x-shockwave-flash'), ### 4 = SWF // A. Duplicated MIME type
array (IMAGETYPE_PSD => 'psd', "mime_type" => 'image/psd'), ### 5 = PSD
array (IMAGETYPE_BMP => 'bmp', "mime_type" => 'image/bmp'), ### 6 = BMP
array (IMAGETYPE_TIFF_II => 'tiff', "mime_type" => 'image/tiff'), ### 7 = TIFF (intel byte order)
array (IMAGETYPE_TIFF_MM => 'tiff', "mime_type" => 'image/tiff'), ### 8 = TIFF (motorola byte order)
array (IMAGETYPE_JPC => 'jpc', "mime_type" => 'application/octet-stream'), ### 9 = JPC // B. Duplicated MIME type
array (IMAGETYPE_JP2 => 'jp2', "mime_type" => 'image/jp2'), ### 10 = JP2
array (IMAGETYPE_JPX => 'jpf', "mime_type" => 'application/octet-stream'), ### 11 = JPX // B. Duplicated MIME type
array (IMAGETYPE_JB2 => 'jb2', "mime_type" => 'application/octet-stream'), ### 12 = JB2 // B. Duplicated MIME type
array (IMAGETYPE_SWC => 'swc', "mime_type" => 'application/x-shockwave-flash'), ### 13 = SWC // A. Duplicated MIME type
array (IMAGETYPE_IFF => 'aiff', "mime_type" => 'image/iff'), ### 14 = IFF
array (IMAGETYPE_WBMP => 'wbmp', "mime_type" => 'image/vnd.wap.wbmp'), ### 15 = WBMP
array (IMAGETYPE_XBM => 'xbm', "mime_type" => 'image/xbm') ### 16 = XBM
);
if((is_int($image_type)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){
$extension = $image_type_identifiers[$image_type-1]; // -1 because $image_type_identifiers array starts at [0]
$extension = $extension[$image_type];
}
elseif(is_string($image_type) AND (($image_type != 'application/x-shockwave-flash') OR ($image_type != 'application/octet-stream'))){
$extension = match_mime_type_to_extension($image_type, $image_type_identifiers);
}
else
{
$extension = INVALID_IMAGETYPE;
}
if(is_bool($include_dot)){
if((false != $include_dot) AND (INVALID_IMAGETYPE != $extension)){
$extension = '.' . $extension;
}
}
else
{
$extension = INVALID_IMAGETYPE;
}
return $extension;
}
}
function match_mime_type_to_extension($image_type, $image_type_identifiers){
// Return from loop on a match
foreach($image_type_identifiers as $_key_outer_loop => $_val_outer_loop){
foreach($_val_outer_loop as $_key => $_val){
if(is_int ($_key)){ // Keep record of extension for mime check
$extension = $_val;
}
if($_key == 'mime_type'){
if($_val === $image_type){ // Found match no need to continue looping
return $extension; ### Return
}
}
}
}
// Compared all values without match
return $extension = INVALID_IMAGETYPE;
}
$extension = image_type_or_mime_type_to_extension($image_type, $include_dot);
return $extension;
}
?>
Model function:
public function file_upload($folder, $allowed_type, $max_size = 0, $max_width = 0, $max_height = 0)
{
$folder = $this->path . $folder;
$files = array();
$count = 0;
foreach ($_FILES as $key => $value) :
$file_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$file_name = $this->global_functions->char_replace($file_name, '_');
$count++;
$config = array(
'allowed_types' => $allowed_type,
'upload_path' => $folder,
'file_name' => $file_name,
'max_size' => $max_size,
'max_width' => $max_width,
'max_height' => $max_height,
'remove_spaces' => TRUE
);
$this->load->library('image_lib');
$this->image_lib->clear();
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
var_dump($error);
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
This function is working partially. Files are being uploaded to the selected folder, but I am getting this error: You did not select a file to upload. and getting FALSE as a result? What seems to be a problem? (form is using form_open_multipart)
Please make sure that you have this name of your file tag field:
$key='userfile' //which is name of input type field name
Are any of your file inputs empty when this happens? $_FILES will contain an array of "empty" data if there is no file specified for the input. For example, my file input name is one, and I submitted it without specifying a file:
Array
(
[one] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
You should check if the file data is empty before processing the upload. PHP's is_uploaded_file() is useful for this.
I'm absolutely stuck on this... checked all related stackoverflow posts and nothing has helped. Using Phil's REST Server / Client setup in Codeigniter and can insert normal entries but cannot upload multiple images, actually even a single image.
I can't really work out how to debug the REST part, it just returns nothing.
I have this array coming in from the view:
Array
(
[1] => Array
(
[name] => sideshows.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phppYycdA
[error] => 0
[size] => 967656
)
[2] => Array
(
[name] => the-beer-scale.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpCsiunQ
[error] => 0
[size] => 742219
)
[3] => Array
(
[name] => the-little-lace.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpXjT7WL
[error] => 0
[size] => 939963
)
[4] => Array
(
[name] => varrstoen-australia.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpcHrJXe
[error] => 0
[size] => 2204400
)
)
I am using this helper method I found to sort out multiple file uploads:
function multifile_array()
{
if(count($_FILES) == 0)
return;
$files = array();
$all_files = $_FILES['files']['name'];
$i = 0;
foreach ($all_files as $filename) {
$files[++$i]['name'] = $filename;
$files[$i]['type'] = current($_FILES['files']['type']);
next($_FILES['files']['type']);
$files[$i]['tmp_name'] = current($_FILES['files']['tmp_name']);
next($_FILES['files']['tmp_name']);
$files[$i]['error'] = current($_FILES['files']['error']);
next($_FILES['files']['error']);
$files[$i]['size'] = current($_FILES['files']['size']);
next($_FILES['files']['size']);
}
$_FILES = $files;
}
This function is being called within the API controller:
public function my_file_upload_post() {
if( ! $this->post('submit')) {
$this->response(NULL, 400);
}
$data = $this->post('data');
multifile_array();
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
foreach ($data as $file => $file_data) {
$this->upload->do_upload($file);
//echo '<pre>';
//print_r($this->upload->data());
//echo '</pre>';
}
if ( ! $this->upload->do_upload() ) {
return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
} else {
$upload = $this->upload->data();
return $this->response($upload, 200);
}
}
I am happy to share my code, I did manage to get multiple files uploading no worries, but just trying to set it up with the API so I can call it from an external website, internally or an iPhone. Help would be appreciated.
Cheers
Update:
Here is the code from the API Controller:
function upload_post() {
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
return $this->response(array('error' => var_export($this->post('file'), true)), 404);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $this->response(array('error' => $data['upload_data']), 404);
}
return $this->response(array('success' => 'successfully uploaded' ), 200);
}
This works if you go directly to the API from the form, but you need to put in the username and password within the browser. If I run this via the controller then it can't find the images.
This is not exactly what you asked for, but this is what I used to solve this problem. A PHP/jQuery upload widget!
http://blueimp.github.com/jQuery-File-Upload/