This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have the following code witch I have just found out that I can upload any kind of file (.png.jpg .txt etc) but I am also unsure were to place $data[success] = TRUE so that it shows after the page has been reloaded and the functions have been run. How could I also do this with the error messages if there was an error?
Controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Addimage extends CI_Controller {
function __construct(){
parent::__construct();
}
function index() {
if(!$this->session->userdata('logged_in')) {
redirect('admin/home');
}
// Main Page Data
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = 'Add Gallery Image';
$data['content'] = $this->load->view('admin/addimage',NULL,TRUE);
$this->load->view('admintemplate', $data);
//Set Validation
//$this->form_validation->set_rules('userfile', 'userfile', 'trim|required');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
if($this->form_validation->run() === TRUE) {
//Set File Settings
$config['upload_path'] = 'includes/uploads/gallery/';
$config['allowed_types'] = 'jpg|png';
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()) {
$error = array('imageError' => $this->upload->display_errors());
}
else{
$data = array('upload_data' => $this->upload->data());
$data['success'] = TRUE;
$config['image_library'] = 'GD2';
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['new_image'] = 'includes/uploads/gallery/thumbs/';
$config['create_thumb'] = 'TRUE';
$config['thumb_marker'] ='_thumb';
$config['maintain_ratio'] = 'FALSE';
$config['width'] = '200';
$config['height'] = '150';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
$file_info = $this->upload->data();
$data = array(
'description' => $this->input->post('description', TRUE),
'imagename' => $file_info['file_name'],
'thumbname' =>$file_info['raw_name'].'_thumb'.$file_info['file_ext']
);
$this->image_model->addImage($data);
}
}
}
View:
<?php
//Setting form attributes
$formAddImage = array('id' => 'addImage', 'name' => 'addImage');
$imageImage = array('id' => 'userfile', 'name' => 'userfile', 'placeholder' => 'File Location*');
$imageDescription = array('id' => 'description','name' => 'description','placeholder' => 'Image Description*');
if($success == TRUE) {
echo '<section id = "validation">Image Uploaded</section>';
}
?>
<section id = "validation"><?php echo validation_errors();?></section>
<?php
echo form_open_multipart('admin/addimage', $formAddImage);
echo form_fieldset();
echo form_upload($imageImage);
echo form_textarea($imageDescription);
echo form_submit('submit','Submit');
echo form_fieldset_close();
echo form_close();
?>
if(!$this->upload->do_upload()) {
$status = array('imageError' => $this->upload->display_errors());
}
else
{
$status = 'Success message'; // or just true
// etc
}
then in your view:
if($status==TRUE)
{
// your success
}
else
{
// aw..somethings's gone wrong, print_r($status);
{
So essentially use one variable.
This is also a good example of when to use flashdata, which is exactly for these purposes.
if(!$this->upload->do_upload())
{
$this->session->set_flashdata('message', 'Sorry, error...');
}
else
{
$this->session->set_flashdata('message', 'Success!');
}
You can of course pass your array of data to set_flashdata if needed.
Related
I know it could be a duplicate but i need a bit more help in that.
I have started working on making api for an android application in codeigniter. And currently working on making api for uploading an image.. I am using https://github.com/chriskacerguis/codeigniter-restserver
using postman to upload images to test my API but
but i am getting something like
'------WebKitFormBoundaryXkKFa0QV2XVs0EoK
Content-Disposition:_form-data;_name' => string '"filesss"; filename="17264394_1739947152983817_1705887364349350305_n.jpg"
Content-Type: image/jpeg
�����JFIF����������Photoshop 3.0�8BIM������g�Vnlfejt43YHm4REx3e4k(�bFBMD01000abe0300002f19000082320000643300004b3400002f4d0000c46f0000d3750000b8780000b07b000096cd0000��ICC_PROFILE���lcms��mntrRGB XYZ
Now can any one help me how to be able to save the image on my server
below is my code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . './libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Update_image extends REST_Controller{
function __construct(){
parent::__construct();
$models[] = 'Quiz_model';
$models[] = 'Users_model';
$this->load->model($models);
$libs[] = 'form_validation';
$libs[] = 'image_lib';
$libs[] = 'email';
//$libs[] = 'rest';
$this->load->library($libs);
$helpers[] = 'file';
$helpers[] = 'security';
$helpers[] = 'url';
$helpers[] = 'string';
$this->load->helper($helpers);
}
function index_post(){
$users_id = $this->input->post('users_id');
$users_id = 6;
$config['upload_path'] = './public/user_images/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = ; // for 5mb file
$config['max_width'] = 5000;
$config['max_height'] = 5000;
$this->load->library('upload', $config);
if(!$this->upload->do_upload('users_image')){
$error = array('error' => $this->upload->display_errors('<span>','<span>'));
$data['msg'] = error('Please Fix the errors below');
$data['file_upload_error'] = formErrorParse($this->upload->display_errors());
$this->form_validation->set_message('quiz_image', implode('<br/>', $error));
$response['status'] = 0;
$response['msg'] = strip_tags($this->upload->display_errors());
}else{
$uploadStat = $this->upload->data();
$img_config['image_library'] = 'gd2';
$img_config['source_image'] = './public/uploads/user_images/'.$uploadStat['file_name'];
$img_config['new_image'] = './public/uploads/user_images/thumbnail/'.$uploadStat['file_name'];
//$img_config['create_thumb'] = TRUE;
$img_config['maintain_ratio'] = TRUE;
$img_config['width'] = 150;
$img_config['height'] = 150;
$this->image_lib->clear();
$this->image_lib->initialize($img_config);
$this->image_lib->resize();
$updates['users_images'] = $uploadStat['file_name'];
$cond['users_id'] = $users_id;
$this->db->update('users', $updates, $cond);
$response['status'] = 1;
$response['msg'] = 'Image Uploaded';
}
$this->response($response, 200);
}
}
I had exactly same problem as you.
But solved after removing Content-Type from headers in postman.
Then you'll get data in $_FILES.
Make sure your php version is 5.6 or above,i had the same problem and solved it by switching to php version 7.
I have found some examples of making the uploads optional but so far it hasn't work for me. I might have missed something so I'm hoping someone might catch it? This is the link to what I am following
https://blog.smalldo.gs/2013/03/optional-file-upload-field-codeigniter/
So far I am able to edit the product if I don't upload a file but if I upload a file, I get a you did not select a file to upload error. Please help. Thank you.
Controller
public function editProduct(){
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
$this->form_validation->set_rules('inputproductname', 'Name', 'trim|required');
$this->form_validation->set_rules('inputproductdescription', 'Description', 'trim|required');
$this->form_validation->set_rules('inputproductprice', 'Price', 'trim|required');
$inputproductname = $this->input->post('inputproductname');
$inputproductdescription = $this->input->post('inputproductdescription');
$inputproductprice = $this->input->post('inputproductprice');
$inputdateadded = date('Y-m-d');
$inputcurrentproductid = $this->input->post('inputcurrentproductid');
$inputcurrentproductstatus = $this->input->post('inputcurrentproductstatus');
$config['upload_path'] = $this->getProductImageFolderPath();
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 3000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $inputproductname;
$this->load->library('upload', $config);
if($this->form_validation->run()==false){
$data['product'] = $this->ProductsModel->getProduct($inputcurrentproductid);
$data['edit'] = "true";
$data['message']='';
$data['inputcurrentproductid'] = $inputcurrentproductid;
$data['inputcurrentproductstatus'] = $inputcurrentproductstatus;
$this->load->view('control/controlMenu/navigationLink');
$this->load->view('control/controlProducts/productDetail',$data);
$this->load->view('control/controlMenu/navigationJquery');
}else{
if(isset($_FILES['upload'])&&$_FILES['upload']['size']>0){
if(!$this->upload->do_upload()){
$this->session->set_flashdata('Form',$this->upload->display_errors());
redirect('Control/ProductDetail/'.$inputcurrentproductid."/".$inputcurrentproductstatus);
}else{
$extension = $this->upload->data('file_ext');
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice,
'imagePath'=>$config['upload_path'].$config['file_name'].$extension,
'dateAdded'=>$inputdateadded
);
$this->db->trans_start();
$this->ProductsModel->editProduct($inputcurrentproductid,$productdetails);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products');
}
if($error!=''){
$this->session->set_flashdata('Form',$error["message"]);
redirect('/Control/Products');
}
}
}else{
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice
);
$this->db->trans_start();
$this->ProductsModel->editProduct($inputcurrentproductid,$productdetails);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products');
}
if($error!=''){
$this->session->set_flashdata('Form',$error["message"]);
redirect('/Control/Products');
}
}
}
You didn't tell the upload library from which field to take the file.
$this->upload->do_upload() // <-- no argument for this method provided
If no field name is provided, by default it tries to get the file from userfile field [docs], but your file input is called upload as seen in the code sample. So you should do
if(!$this->upload->do_upload("upload")){
Also, note that on the client side the form with file field should be declared as
<form method="post" action="some_action" enctype="multipart/form-data" />
otherwise file field will be empty too.
I have a multipart/form-data with an image upload and some personal data, so I want to include file upload in form validation, I can successfully do this.
However, I now find that there is an issue, ie even if my other form fields have errors and upload file field with no error, then image uploads to folder, how to prevent this, I mean, in my case, If name, email, file fields validation is ok then only file should upload, if name filed validation fails and file field validation ok then file should not upload
here is the code I use:
In Controller:
<?php
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
'profile_img'=>array('field'=>'profile_img', 'label'=>'Design', 'rules'=>'callback__profile_upload')
);
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
function _profile_upload(){
if($_FILES['profile_img']['size'] != 0 && !empty($_FILES['profile_img']) ){
$upload_dir = './profile_pics/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'profile_img_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->upload->initialize($config);
if (!$this->upload->do_upload('profile_img')){
$this->form_validation->set_message('_profile_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('_profile_upload', "No file selected");
return false;
}
}
IN VIEW:
<?php echo form_open_multipart();?>
<?php $name_err = (!empty(form_error('name'))) ? 'err' : ' ';
echo form_input('name',set_value('name'), array('placeholder'=>'Name','class'=>" {$name_err } "));
?>
<?php $email_err = (!empty(form_error('email'))) ? 'err' : ' ';
echo form_input('email',set_value('email'), array('placeholder'=>'EMail','class'=>" {$email_err } "));
?>
<?php
echo form_error('profile_img');
echo form_upload(array('name' =>'profile_img', 'class' => 'inputfile inputfile-4', 'id' => 'profile_img'));
?>
<li><input type="submit" class="special" value="Submit" /></li>
Try once like this.I think for images not need to set rules like other fields.
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
);
And
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
if ($this->_profile_upload()) { //return true if file uploaded successfully otherwise error
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
}
yes that is very obvious that your file get uploads even any other fields' validation failed. You have to initiate image uploading only after form validation success.
For that simply validate file specific requirement in that callback, and do actual uploads after successful form validation.
I have got a solution from codexWorld, I have asked same question over there, and they replied with a tutorial, If anybody still looking for a solution here is the link
http://www.codexworld.com/codeigniter-file-upload-validation/
in the validation call back, we just want to do the file type check
public function _profile_upload($str){
$allowed_mime_type_arr = array('image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('_profile_upload', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('_profile_upload', 'Please choose a file to upload.');
return false;
}
}
and in the main function we just want to do the same as normal, using do_upload and specifying the upload config items, anyhow there will be a second file type check when the function executes, I think that doesn't matter. The code will look like this::
public function profile()
{
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'uploads/files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
//upload file to directory
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
/*
*insert file information into the database
*.......
*/
}else{
$data['error_msg'] = $this->upload->display_errors();
}
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
I am having problem dealing with File Uploads in CodeIgniter 2.2.
I am able to create its specific folder destination, but I am unable to upload the file that I have selected.
Here's my Controller:
function create_report()
{
if($this->session->userdata('logged_in'))
{
$this->create_model->set_report();
$this->session->set_flashdata('message', 'Success! You created a Report!');
#$redirect($_SERVER['HTTP_REFERER'], 'refresh');
}
else
{
$this->session->set_flashdata('message', 'Oops! You have to Login');
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
and here is my Model:
function set_report()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
if($_FILES['userfile']['name'] != NULL)
{
$main_dir = './FILES/'.$this->input->post('patientname').'/';
// Check if User Folder is already created. Create New if none exist
if(!is_dir($main_dir)){
mkdir($main_dir, 0777);
}
$target_dir = './FILES/'.$this->input->post('patientname').'/'.$this->input->post('session_id').'/';
// Check if Session Folder is already created. Create New if none exist
if(!is_dir($target_dir)) {
mkdir($target_dir, 0777);
}
$config['upload_path'] = './FILES/'.$this->input->post('patientname').'/'.$this->input->post('session_id').'/';
$config['allowed_types'] = 'gif|jpg|png|docx|xlsx|doc|pdf|csv|zip|rar|7zip|ppt|pptx';
$this->load->library('upload', $config);
$data2 = array('upload_data' => $this->upload->data());
}
$data = array(
'session_id' => $this->input->post('session_id'),
'report_creator' => $session_data['username'],
'report_patientname' => $this->input->post('patientname'),
'report_patientid' => $this->input->post('patientid'),
'report_subject' => $this->input->post('subject'),
'report_description' => $this->input->post('description'),
'report_time' => $this->input->post('date'),
'report_date' => $this->input->post('time')
);
return $this->db->insert('session_reports', $data);
}
}
I've been trying to solve this and I haven't figure out the key.
I hope anyone could help me with this.
I believe, I have failed to initialize the config.
$this->upload->initialize($config);
That solved my problem. Thank you everyone
Remove this
$data2 = array('upload_data' => $this->upload->data());
and replace this to that
if (!$this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
Load Library
$this->load->library('upload', $config);
Alternately you can set preferences by calling the initialize() method. Useful if you auto-load the class:
$this->upload->initialize($config);
Codeigniter file Upload
May I ask for your help guys!
I am trying to upload a file and passing all the data to codeigniter controller using jquery.
my view file:
<div class="form-group">
<label class="col-md-4 control-label">Item Image</label>
<div class="col-md-8">
<input class="form-control" type="file" placeholder="" id="itemImage" name="itemImage" data-parsley-required="true" />
</div>
</div>
<button type="button" onclick="add_item();">Sumit</button>
<script>
function add_item(){
$.post('<?php echo site_url('admin_newitem/add_item'); ?>',
{
itemId : $('#itemId').val(),
itemImage : $('#itemImage').val()
},
function(data){
if(data.result=='SUCCESS'){
$('#itemId').val('');
$('#itemImage').val('');
//show success
}else{
//show error
}
},'json'
);
}
</script>
My controller:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if(!$itemImage){
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}
I was able to get the ItemId, and ItemImage but when I check the folder where the image is suppose to be located, it's not there. I think I fail to capture the real file, so, is there a way for me to get this done?
As you suggest, I believe that you are forgetting to actually do the upload, the code igniter documentation might help:
http://www.codeigniter.com/user_guide/libraries/file_uploading.html
With this correctly implemented, I think your code should look something similar to:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
//THE MISSING LINE
if($this->upload->do_upload()){
//THE FILE HAS NOW BEEN UPLOADED
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}else{
//NO FILE UPLOADED
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
}
My initial thinking, having used CI and tried to do this same thing, is that you can't do file uploads via AJAX without a special plugin such as this:
http://malsup.com/jquery/form/
Specifically, this file upload portion:
http://malsup.com/jquery/form/#file-upload
Simply trying to send a post with the val of a file input will not work, I don't believe - though maybe more modern browsers are able to handle that now.