Use two file upload Button in codeigniter - php

I'm trying to use two file upload buttons in codeigniter like below
<label class="control-label" for="default">PO File</label>
<input type="file" id="po_file" name="po_file" multiple="multiple" >
<label class="control-label" for="default">Invoice File</label>
<input type="file" id="in_file" name="in_file" multiple="multiple" >
in controller
$file1 = $_FILES['po_file']['name'];
$file2 = $_FILES['in_file']['name'];
$config['upload_path'] = $pathToUpload;
$config['allowed_types'] = 'pdf';
$config['overwrite' ] =TRUE;
$config['max_size'] =0;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
echo $this->upload->display_errors();
// $this->load->view('file_view', $error);
}
else
{
$this->upload->do_upload(file1);
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
}
I tried like this but it gave
You did not select a file to upload.
Any help how to do this???
thank you

Seeing your form in the question, I'm assuming that you want two files to be uploaded from two different input fields. Is that it ?
So, doing it in your way, your form should be as :
<form enctype="multipart/form-data" method="post"> <!-- enctype="multipart/form-data" is must, method 'post' or 'get' is depend on your requirement -->
<?php
if( !empty( $notification ) )
{
echo '
<p>Notifications : </p>
<p>'.$notification.'</p>'; <!-- For the status of the uploaded files ( error or success ) -->
}
?>
<label for="default">PO File</label>
<input type="file" name="po_file"> <!-- no need to add "multiple" attribute, unless you want multiple files to be uploaded in the same input field-->
<label for="default">Invoice File</label>
<input type="file" name="in_file">
<input type="submit" name="upload">
</form>
And your controller should be as :
class Image extends CI_Controller {
private $data; // variable to be used to pass status of the uploaded files ( error or success )
function __construct()
{
// some code
}
public function upload()
{
$this->data['notification'] = '';
if( $this->input->post('upload') ) // if form is posted
{
// setting the config array
$config['upload_path'] = 'uploads/'; // $pathToUpload ( in your case )
$config['allowed_types'] = 'pdf';
$config['max_size'] = 0;
$this->load->library('upload', $config); // loading the upload class with the config array
// uploading the files
$this->lets_upload( 'po_file' ); // this function passes the input field name from the form as an argument
$this->lets_upload( 'in_file' ); // same as above, function is defined below
}
$this->load->view('form', $this->data); // loading the form view along with the member variable 'data' as argument
}
public function lets_upload( $field_name ) // this function does the uploads
{
if ( ! $this->upload->do_upload( $field_name )) // ** do_upload() is a member function of upload class, and it is responsible for the uploading files with the given configuration in the config array
{
$this->data['notification'] .= $this->upload->display_errors(); // now if there's is some error in uploading files, then errors are stored in the member variable 'data'
}
else
{
$upload_data = $this->upload->data(); // if succesful, then infomation about the uploaded file is stored in the $upload_data variable
$this->data['notification'] .= $upload_data['file_name']." is successfully uploaded.<br>"; // name of uploaded file is stored in the member variable 'data'
}
}
}
Now suppose, you want a new image file to be uploaded in a different location or whatever, from the same form; then in the config array, you only have to change the array elements which you want to be different as :
$config['upload_path'] = '/gallery';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
Then you have to initialize the config array as :
$this->upload->initialize($config); // *** this is important ***
and then you have to load the upload class with this new config as :
$this->load->library('upload', $config);
and now you can call the lets_upload() function :
$this->lets_upload( 'img_file' );
in the upload() function.

first in your php.ini
file_uploads = On
Second be sure of that
<form action="controller/action" method="post" enctype="multipart/form-data">
third check that on codeigniter documentaion about upload file .
https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
don't forget the extension of files allowd

If you see upload.php library file under system folder then you'll know that CI takes 'userfile' field name as default, So when you do
if ( ! $this->upload->do_upload())
{
echo $this->upload->display_errors();
// $this->load->view('file_view', $error);
}
//Passing parameter empty, then CI search for 'userfile'.
Try passing field name as you have done in else condition, or setting one of the input field name to 'userfile'.

Related

Invalid argument supplied for foreach() in Form and Multi Image upload in Laravel

The Form upload and the product image as featured image and other other images using the store function of laravel
use App\Productimage;
use App\Products;
public function store(Request $request)
{
$featured = $request->featured_image->store('products_featured');
$product = Products::create([ //uploading successfully
'name'=>$request->name,
'featured_image' => $featured,
]);
foreach ($request->photos as $photo) { //error
$filename = $photo->store('product_images');
Productimage::create([
'product_id' => $product->id,
'image_name' => $filename,
]);
}
return back();
}
Make sure $request->photos is an array and your form is a multipart/form-data.
You need to send your files from your blade (or wherever your are sending them from) in photos[], e.g.
<input type="file" name="photos[]"/>
P.S - In your controller method, you should access $request->photos like this $request->file('photos'). - This is not the cause of your error but if you don't do this, you'll get a JSON object instead of file content.
you form should have enctype="multipart/form-data" and input type file is array
foreach ($request->file('photos') as $photo) { //error
$filename = $photo->store('product_images');
Productimage::create([
'product_id' => $product->id,
'image_name' => $filename,
]);
}
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="photos[]"/>

I want to upload image in codeigniter but my code does not work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
view/image.php:
<form action="upload.php" method="post">
<h3>Image Upload Form</h3>
<input type="file" name="pic" tabindex="2" required>
<input type="text" name="alt" placeholder="Image Alt Text" tabindex="1"
required>
<button type="submit" id="img-submit" data-
submit="Sending">Submit</button>
</form>
controller/upload.php:
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->helper('form');
}
function image()
{
$this->load->view('pages/image');
}
function upload()
{
$data = array(
'image_url' => $this->input->$_FILES['pic']['name'],
'alt' => $this->input->post('alt')
)
}
models/upload_m.php:
<?php
class pages_m extends CI_Model {
function __construct()
{
parent::__construct();
}
function upload($data)
{
return $this->db->insert('image',$data);
}
}
?>
When I try to access the page through localhost/codeigniter/index.php/pages/image it shows error 404 not found. Also would be grateful if someone could check my code for possible mistakes I might have made? Thanks in advance!
i think you forgot to write enctype in form tag.
use this code
<form action="upload.php" method="post" enctype="multipart/form-data">
<h3>Image Upload Form</h3>
<input type="file" name="pic" tabindex="2" required>
<input type="text" name="alt" placeholder="Image Alt Text" tabindex="1"
required>
<button type="submit" id="img-submit" data-
submit="Sending">Submit</button>
</form>
First thing to do should be correcting your form:
<form action="upload.php" method="post" enctype="multipart/form-data">
Then you should wrap your controller code in this and take care at typo because this things are case sensitive
(rename your controller using upper case for first letter:
Upload.php):
class Upload extends CI_Controller {
}
Then let's move to your model (Pages_Model.php):
class Page_Model extends CI_Model {
}
Also I do not see where you load your model in controller. You have to do something like this either in your controller's constructor or in the function you need to use model's functions:
$this->load->model('Page_Model');
And when you want to use the function from model you have to do it like this:
$this->Page_Model->function_name($data);
And you can always check codeigniter's website for documentation. It's very well written and easy to understand. Cheers!
LE: I forgot about upload.
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$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);
}
}
Usefull link: https://www.codeigniter.com/userguide3/libraries/file_uploading.html
This is an example function. In your code you didn't upload something. Your database can't keep files. You use it for filenames (in this case).
form attrtibute enctype="multipart/form-data" is missing which is required when you are using forms that have a file upload control. For more details https://www.w3schools.com/tags/att_form_enctype.asp. You can also use CI helper funtion for declaring form tag form_open_multipart
The form action URL not correct which why you are getting 404 error. For more details https://www.codeigniter.com/userguide3/tutorial/static_pages.html
You didn't include CI upload libraries and didn't follow basic steps mentioned in CI tutorial. Please find upload tutorial here https://www.codeigniter.com/userguide3/libraries/file_uploading.html
Welcome for any queries.
Add this function in your controller and try.
public function doupload()
{
$upload_path="https://localhost/project/profile"
$uid='10'; //creare seperate folder for each user
$upPath=upload_path."/".$uid;
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config = array(
'upload_path' => $upPath,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000",
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('pic'))
{
$data['imageError'] = $this->upload->display_errors();
}
else
{
$imageDetailArray = $this->upload->data();
$image = $imageDetailArray['file_name'];
}
}

How to store file images into mysql (Codeigniter)

I tried to upload file images into mysql using Codeigniter
This is likely my upload view:
<label>Upload File</label>
<input type="file" class="form-control" name="images">
</div>
I've done with image name, description, etc.
I tried to save it into database, just like normal input form.
The result, column "images" cannot be null. I have set column "images" with varbinary(3000)
Am I doing it wrong?
EDITED:
My Controller:
public function save(){
$this->gallery_model->save_foto();
$this->session->set_flashdata('msg','FOTO BERHASIL DI UPLOAD');
redirect(base_url('gallery'));
}
My Model
<?php
class Gallery_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function save_foto(){
$data['id'] = date('U');
$data['nm_foto'] = $this->input->post('nm_foto');
$data['username'] = $this->input->post('username');
$data['tanggal'] = date('j F Y');
$data['images'] = $this->input->post('images');
$data['deskripsi'] = $this->input->post('deskripsi');
$this->db->insert( 'gallery', $data );
}
}
You can't directly upload image into database , Insert image path
For upload image form form add
enctype="multipart/form-data"
in form .
For more help regarding image upload in codeigniter
Codeigniter Image Upload
You can store images but its not advisable.
The "correct" way to do it is to store the files somewhere on your server and store the URI in the database.
The problem is that images can be quite large, this can result in a big load on your database which is unnecessary. When you work on a larger scale project you may have multiple database that need to be synchronised, when you database is larger then it need to be you unnecessary slow down your network.
If you still want the image stored in the datebase, you can store it as an BLOB type. See the MySQL documenation
You can insert it then with the following example code
$data['image'] = file_get_contents($_FILES['image']['tmp_name']);
If someone met an error and getting tired just like me, here's the simple way and codes you can upload [images] into your assets folder
In Controller
public function upd_gallery(){
$file = $this->input->post('img_name').".jpg";
move_uploaded_file($_FILES['images']['tmp_name'], './wheretosave/etc/etc'.$file);
redirect( base_url().'gallery');
}
Set application -> config -> routes
$route['gallery/upload2'] = 'gallery/upd_gallery';
Put this to your view
<?php
$ff = './where-to-save/etc/'.$this->input->post('img_name').'.jpg';
?>
<form action="<?= base_url()?>gallery/upload2" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="img_name" required="required">
</div>
<div class="form-group">
<input type="file" class="form-control" name="images">
</div>
<div class="form-group">
<button type="submit" class="btn btn-common" value="Update"> Upload</button>
</div>
</div>
</div>
Of course, this way is very simple. You just have to name your image and save it
Saving image in database is NOT good practice. You can use following code to store files on your server's file system.
$userfile= $this->input->post('userfile'); //gets image name only
if ($_FILES['userfile']['name'] != '') { //to check if you've selected any file
$path = './path/to/folder';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['max_size'] = '0';
if (!is_dir($config['upload_path']))
die("THE UPLOAD DIRECTORY DOES NOT EXIST");
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
return "UPLOAD ERROR ! " . $this->upload->display_errors();
}
else {
$filepath = $this->upload->data();
$doc_path = $filepath['file_name'];
return $doc_path;
}
}

CodeIgniter: “The filetype you are attempting to upload is not allowed.” i need upload .dwg file

public function step8()
{
$data['application']=$this->license_m->get_byID($this->session->userdata('L_ID'))->row();
if($this->input->post('submit')){
$data= array(
'DESC' => $this->input->post('DESC',true),
'L_ID' => $this->session->userdata('L_ID')
);
if($_FILES['FILE_URL']['name'])
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'dxf|dwg|gif|jpg|png|pdf|doc|docx|txt|rar|zip|bmp';
$config['max_size'] = '0';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('FILE_URL'))
echo json_encode($this->upload->display_errors('<p>','</p>'));
else
{
$upload_data = $this->upload->data();
$FILE_URL=$upload_data['file_name'];
$data['FILE_URL']=$FILE_URL;
$status=$this->license_m->add_attachment($data);
}}}
*/
Go in application/config/mimes.php file and extend the allowed file types array with the dwg. Add the following line anywhere in the $mimes array -
'dwg' => 'application/acad'
If you want to extend the list with more mime types, this might be helpfull.
go in ci/application/config/mimes.php file and extend the allowed file types array with the dwg. add this line anywhere in the $mimes array-
'dwg' => 'application/acad'
basically if you want to add any kind of filetype you have to add it like this in ci/application/config/mimes.php
'extension' => 'application/mimetype'
and if there is a file type which have more than one mime type we have to define it in ci/application/config/mimes.php like
'extension' => array('application/mimetype','application/mimetype')
for example-:
'ogg' => array('audio/ogg', 'video/ogg', 'application/ogg')
and remember if you are not declaring it at last then you have to put , after every declaration.....

upload file to sql table using a path

I'm trying to upload a file to a MySQL table using a path (the file will be save on the server asd in the table a link for him). Here is what I've done:
My view is:
<div class="row">
<?php echo $form->labelEx($model,'doc_ordered_recieved'); ?>
<?php echo $form->fileField($model,'doc_ordered_recieved'); ?>
<?php echo $form->error($model,'doc_ordered_recieved'); ?>
</div>
My model is:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'insert,update'),
and my controller is:
public function actionCreate()
{
$model=new Orders;
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$uploadedFile = CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->doc_ordered_recieved== null || empty($model->doc_ordered_recieved)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->doc_ordered_recieved= $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/files/'. $model->doc_ordered_recieved);
// redirect to success page
}
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
The table is defined as varchar is that ok????
The file should be saved in d:\xampp\htdocs\filse
Please help me it always says: doc_ordered_recieved can't be blank

Categories