I have tried all solutions but I can't tell what's wrong. Codeigniter keeps telling me that there's no file uploaded. I created the folder at the root of the project. I've seen other similar questions but I can't manage to make it work with their solutions.
This is my controller:
public function index() {
$this->form_validation->set_rules('name', 'name', 'required|trim|max_length[45]');
$this->form_validation->set_rules('type_id', 'type', 'required|trim|max_length[11]');
$this->form_validation->set_rules('stock', 'stock', 'required|trim|is_numeric|max_length[11]');
$this->form_validation->set_rules('price', 'price', 'required|trim|is_numeric');
$this->form_validation->set_rules('code', 'code', 'required|trim|max_length[45]');
$this->form_validation->set_rules('description', 'description', 'required|trim|max_length[45]');
$this->form_validation->set_rules('active', 'active', 'required|trim|max_length[45]');
$this->form_validation->set_rules('unit_id', 'unit', 'required|trim|max_length[45]');
$this->form_validation->set_rules('userfile', 'File', 'trim');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
$this->load->view('product/add_view');
} else { // passed validation proceed to post success logic
// build array for the model
$form_data = array(
'name' => set_value('name'),
'type_id' => set_value('type_id'),
'stock' => set_value('stock'),
'price' => set_value('price'),
'code' => set_value('code'),
'description' => set_value('description'),
'active' => set_value('active'),
'unit_id' => set_value('unit_id')
);
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
$this->upload->initialize($config); //Make this line must be here.
$imagen = set_value('userfile');
// run insert model to write data to db
if ($this->product_model->product_insert($form_data) == TRUE) { // the information has therefore been successfully saved in the db
if (!$this->upload->do_upload($imagen)) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('product/add_view', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('product/add_view', $data);
}
} else {
redirect('products/AddProduct', 'refresh');
// Or whatever error handling is necessary
}
}
}
This is my view (just showing the part that matters)
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => '');
echo form_open_multipart('products/AddProduct', $attributes); ?>
<p>
<label for="picture">Picture <span class="required">*</span></label>
<?php echo form_error('userfile'); ?>
<?php echo form_upload('userfile')?>
<br/>
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
EDIT: Applying the modification from the answer I get an error 500.
I tried to work on your code. and it worked on me after this changes
$config = array(
'upload_path' => "./uploads/",
'upload_url' => base_url()."uploads/", // base_url()."/uploads/", //added
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload'); //changed
$this->upload->initialize($config); //Make this line must be here.
$imagen = userfile; // $_FILES['userfile']['name'] //changed
If you get The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500 possible error on your syntax, I just add 1 more } at the end of your code. You can check phpinfo() for other information. Also, there might be a problem on your file locations maybe the address you specified or the permissions if your running this on server.
Related
I have tried every possible method but no success. Just trying to upload file using code igniter but not working the error I am getting
<pre>Array
(
[error] => <p>You did not select a file to upload.</p>
)
I have tried in normal core php at my local host that works fine but not working with code igniter. It is simply not picking the file. If I check with var_dump($_FILES['fileToUpload']); the result will be array(0).
Form Code
<form id="contact_form" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>Main/do_upload">
<input type="file" class="form-control" name="fileToUpload" id="fileToUpload">
</form>
Controller Code
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
echo "<pre>";
var_dump($data);
// $this->load->view('upload_success',$data);
}else{
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
}
config
$autoload['libraries'] = array("session", "email", "database");
$autoload['helper'] = array("url", "file", "form");
Is there anything I am not aware of ? Please guide I am stuck here.
You missed input file name in do_upload():
Use :
if(!$this->upload->do_upload('image_file'))
{
//$this->upload->display_errors()
}
else
{
//$this->upload->data()
}
Instead of:
if($this->upload->do_upload())
You miss parameters in $this->upload->do_upload Pleas check below code.
public function do_upload(){
$config = array(
'upload_path' => "assets/uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('fileToUpload'))
{
$data = array('upload_data' => $this->upload->data());
echo "<pre>";
var_dump($data);
// $this->load->view('upload_success',$data);
}else{
$error = array('error' => $this->upload->display_errors());
echo "<pre>";
print_r($error);
}
}
Pass your file upload name in $this->upload->do_upload('fileToUpload')
Ok try to upload file for hours but i get error,
You did not select a file to upload.
my code is in CI
$this->config = array(
'upload_path' => dirname($_SERVER["SCRIPT_FILENAME"])."/uploads/",
'upload_url' => base_url()."uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|doc|xml",
'overwrite' => TRUE,
'max_size' => "1000KB",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $this->config);
if($this->upload->do_upload('logo'))
{
echo "file upload success";
}
else
{
echo $this->upload->display_errors();
}
in view i have
<input type="file" name="logo"/>
when i print_r $_POST i get
Array ( [name_srpski] => tyre [name_english] => Client nametre [logo] => cipele-plava_1.jpg )
Where could be error its very important
Try the following in config:
'upload_path' => FCPATH . "/uploads/", // or use "./uploads/" instead
'max_size' => "1000", // remove the kb from the string. it requires only the number
Try changing $this->load->library('upload', $this->config); to
$this->load->library('upload');
$this->upload->initialize( $this->config );
Also the form type should be multipart
<form method="post" action="some_action" enctype="multipart/form-data" />
I'm very new on cakephp and I try to make an edit function with file replacement but it isn't working. If the file already exists I get an error message.
This is my admin_edit.ctp code:
<td>
<?php if (!empty($this->data['Stock']['filepath'])): ?>
<div class="input">
<label>Uploaded File</label>
<?php
echo $this->Form->input('filepath', array('type'=>'hidden', 'label' => false));
echo $this->Html->link(basename($this->data['Stock']['filepath']),
$this->data['Stock']['filepath']);
?>
</div>
<?php else: ?>
<?php echo $this->Form->input('filename',array('type' => 'file', 'label' => false)); ?>
<?php endif; ?>
</td>
here below stock.php validation code
public $validate = array(
'filename' => array(
// http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::uploadError
'uploadError' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the file upload - filename error',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// http://book.cakephp.org/2.0/en/models/data-validation.html#Validation::mimeType
'mimeType' => array(
'rule' => array('mimeType', array('image/gif','image/png','image/jpg','image/jpeg')),
'message' => 'Invalid file, only images allowed',
'required' => FALSE,
'allowEmpty' => TRUE,
),
// custom callback to deal with the file upload
'processUpload' => array(
'rule' => 'processUpload',
'message' => 'Something went wrong processing your file - process error',
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
)
processUpload :
public function processUpload($check=array()) {
// deal with uploaded file
if (!empty($check['filename']['tmp_name'])) {
// check file is uploaded
if (!is_uploaded_file($check['filename']['tmp_name'])) {
return FALSE;
}
// build full filename
$filename = WWW_ROOT . $this->uploadDir . DS . Inflector::slug(pathinfo($check['filename']['name'], PATHINFO_FILENAME)).'.'.pathinfo($check['filename']['name'], PATHINFO_EXTENSION);
// #todo check for duplicate filename
// try moving file
if (!move_uploaded_file($check['filename']['tmp_name'], $filename)) {
return FALSE;
// file successfully uploaded
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT, "", $filename) );
}
}
return TRUE;
}
Error message :"Something went wrong with the file upload - filename error"
Before saving :
public function beforeSave($options = array()) {
// a file has been uploaded so grab the filepath
if (!empty($this->data[$this->alias]['filepath'])) {
$this->data[$this->alias]['filename'] = $this->data[$this->alias]['filepath'];
foreach (array_keys($this->hasAndBelongsToMany) as $model){
if(isset($this->data[$this->name][$model])){
$this->data[$model][$model] = $this->data[$this->name][$model];
unset($this->data[$this->name][$model]);
}
}
}
return parent::beforeSave($options);
Does anyone help me to find mistake ?
Thanks
I want to have a multiple file upload code.
For example:
Koala.jpg
Penguins.jpg
Jellyfish.jpg
There is input text where the user can set the new name of the image.
The user will now upload the images and the inputted text for new image name is "Animals"
Now, what I want is when this uploaded the output should be Animals1.jpg, Animals2.jpg, Animals3.jpg.
The problem is when I tried to upload all these images, only one image is uploading.
I tried to make research and applied some codes on my program, but still not working.
Controller
public function do_upload() {
$config = array(
'image_library' => 'gd2',
'file_name' => $this->input->post('finame'),
'upload_path' => './public/img/uploads',
'upload_url' => base_url().'public/img/uploads',
'allowed_types' => 'gif|jpg|jpeg',
'max_size' => '1024KB',
'max_width' => '1024',
'max_height' => '768',
'maintain_ratio'=> TRUE,
'overwrite' => false,
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$error_msg = "<div class='alert alert-error'>".$this->upload->display_errors()."</div>";
$error = array('error' => $error_msg);
}
else {
$upload_data = $this->upload->data();
$data['thumbnail_name'] = $upload_data['raw_name']. '_thumb' .$upload_data['file_ext'];
$file_array = array(
'image' => $data['thumbnail_name'],
'image_name' => $upload_data['file_name'],
//'description' => "",
'date_created' => date('Y-m-d H:i:s', now()),
'date_modified' => date('Y-m-d H:i:s', now()),
'author' => $this->session->userdata('username'),
'size' => $upload_data['file_size'],
'type' => $upload_data['image_type'],
'width' => $upload_data['image_width'],
'height' => $upload_data['image_height'],
//'document_name' => $field,
//'department' => $field2,
//'notes' => "",
);
$this->session->set_userdata('image_print', $file_array);
$this->load->database();
$this->db->insert('tbl_image', $file_array);
$data = array('upload_data' => $this->upload->data());
$user_level['records']=$this->user_model->get_records();
$this->load->view('v_dashboard/page/header_view', $user_level);
$this->load->view('v_document/upload/upload_result_view', $data);
$this->load->view('v_dashboard/page/footer_view');
}
}
I have this on my HTML
<label for="file"><strong>Select File To Upload:</strong></label>
<input type="file" name="userfile[]" multiple class="btn transcolor btn-file"/>
<br/><br/>
By the way, I'm using BLOB on my database.
I tried to refer to this links
Ellislab
GitHub
StackOverflow
StackOverflow
CodingLikeASir
You have to run the for loop till the count of the uploaded image file.
Like this:
for ($i=0; $i < count($_FILES['userfile']['name']); $i++)
{
// function to add the image name one by one into database.
}
<?php
$image = array(
'name' => 'userfile',
'id' => 'userfile',
);
$submit = array(
'name' => 'submit',
'id' => 'submit',
'value' => 'Upload'
);
?>
<?php echo form_open_multipart('upload/upload_image', 'id=upload_file'); ?> <!-- must autoload form helper for this -->
<?php echo form_upload($image); ?>
<?php echo form_submit($submit); ?>
<?php echo form_close(); ?>
this is main.php in view folder
<?php
class Upload_model extends CI_Model{
var $original_path;
var $resized_path;
var $thumbs_path;
//initialize the path where you want to save your images
function __construct(){
parent::__construct();
//return the full path of the directory
//make sure these directories have read and write permessions
$this->original_path = realpath(APPPATH.'../uploads/original');
$this->resized_path = realpath(APPPATH.'../uploads/resized');
$this->thumbs_path = realpath(APPPATH.'../uploads/thumbs');
}
function do_upload(){
$this->load->library('image_lib');
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png', //only accept these file types
'max_size' => 2048, //2MB max
'upload_path' => $this->original_path //upload directory
);
$this->load->library('upload', $config);
$image_data = $this->upload->data(); //upload the image
print_r($image_data);
if($image_data){
echo "uploaded";
}else {echo "not upload";}
//your desired config for the resize() function
$config = array(
'source_image' => $image_data['full_path'], //path to the uploaded image
'new_image' => $this->resized_path, //path to
'maintain_ratio' => true,
'width' => 128,
'height' => 128
);
//this is the magic line that enables you generate multiple thumbnails
//you have to call the initialize() function each time you call the resize()
//otherwise it will not work and only generate one thumbnail
$this->image_lib->initialize($config);
$this->image_lib->resize();
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->thumbs_path,
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
//here is the second thumbnail, notice the call for the initialize() function again
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
}
this is my model
and controller only load main.php that allow me select image click submit and then controller call model above to load image
the problem is --> there are no error generate but image and thumbs not uploaded to directory why please?