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;
}
}
Related
I am trying to update an image and other data in a database, but when I update only text data, the image value becomes null or empty.
<form action="/admin/settings/why-us/update/{{$data->id}}" enctype="multipart/form-data" method="POST">
#csrf
<input type="text" class="form-control" name="title" value="{{$data->title}}">
<input type="file" class="form-control" value="{{$data->image}}" name="image">
<button type="submit" class="btn btn-success py-2 px-4 text-white">Update changes</button>
</form>
This a controller
public function updateWhyusPageSetting(Request $request,$id)
{
$title = $request->input('title');
$image = $image = $request->file('image');
dd($image);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('/frontend/images/'), $filename);
$image_upload = $request->file('image')->getClientOriginalName();
}
DB::table('features')
->where('id', $id)
->update([
'title' => $title,
'image' => $image_upload
]);
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
When I input only the title, left out the image, and tried to dump using dd($image);, I got a null value.
When updating the image, it's getting updated very well database.
Now, my question is, how do I make sure the value is captured in the input file <input type="file" class="form-control" value="{{$data->image}}" name="image"> so that when I update other data, it also sends the image value. NB: value="{{$data->image}}" IS NOT capturing the data from database
Try this code
public function updateWhyusPageSetting(Request $request,$id){
$data = [];
$data['title'] = $request->input('title');
if($request->hasFile('image')) {
$image = $request->file('image');
$image->move(public_path('/frontend/images/'),$imageName = $image->hashName()); //hashName() will generate image name with extension
$data['image'] = $imageName; // here if user uploads an image, it will add to data array then add to DB.
}
DB::table('features')
->where('id', $id)
->update($data); // if a user uploaded an image will add. if not, a previous image will not change
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
Please note you should delete the old images if you don't need anymore
you can use this to delete an old image if you want
(new Filesystem())->delete("full/path/with/image/name.jpg");
I'm trying to upload image-file from frontend in OctoberCMS
I have a model Person and relation:
public $attachOne = [
'photo' => 'System\Models\File'
];
In php-block with upload form:
public function onUploadImage() {
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo = \Input::file('avatar');
$person->save();
}
And my template:
<form method="POST" action="/persons/person/{{person.id}}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_handler" value="onUploadImage">
<input type="file" name="avatar" id="avatar" />
{{ form_token() }}
{{ form_sessionKey() }}
<button type="submit" data-attach-loading>Upload</button>
After submit it saves to DB only path 'http://my-site/storage/app/uploads/public/' and does not upload any files to filesystem. It seems like there are no some permissions, but I can easily upload images from backend.
Where is my error?
You must get the UploadedFile from the request and store it to one of the configured disks. And store the path to the image in the database.
Assume storage/app/public/images is the directory where the uploaded images should be stored.
public function onUploadImage() {
if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
$file = request()->file('avatar');
$filename = $file->getClientOriginalName();
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo = $file->storeAs('images', $filename)
$person->save();
}
}
Here is the solution.
if(request()->hasFile('avatar') && request()->file('avatar')->isValid()) {
$file = new System\Models\File;
$file->data = Input::file('avatar');
$file->is_public = true;
$file->save();
$person = Person::where('id', '=', $this->param('id'))->first();
$person->photo()->add($file);
$person->save();
}
I made an update form wherein in i can edit and update current uploads in my renting shop project.
but i've been having this problem wherein the image isn't changing both in the page and database, but when i checked the storage/public/images it stores the same current image whenever i try to try again.
but the rest in my form is working fine and already changeable except the image.
Here is in my CarsController.php
public function update(Request $request, $id)
{
$car = Car::find($id);
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
if ($request->hasFile('image_location')) {
Storage::disk('public')->delete($car->image_location); // remove the old file.
$path = $request->image_location->store('images', 'public'); // save the new image.
$car->image_location = $path;
}
$car->save();
$request->session()->flash('message', 'The item has been updated.');
return redirect('/selections');
}
Here's the form
<div class="form-group">
<label>Image</label>
<input type="file" class="form-control" name="image_location" required>
</div>
i don't know what could possibly wrong. anyone please enlighten me. Thanks in advance. Anyway the migrated column name is image_location
also here's in my store()
public function store(Request $request)
{
$car = new car;
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
$path = $request->image_location->store('images', 'public');
$car->image_location = $path;
$car->availability = $request->availability;
$car->save();
$request->session()->flash('message', 'The item has been added.');
return redirect('/selections');
}
I'm afraid your code works perfectly for me.
You could try adding some log lines and see where the problem lies:
use Illuminate\Support\Facades\Log;
if ($request->hasFile('image_location')) {
Log::debug('File has been found in request.');
// Check if the old car image exists.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': ' does not exist'));
Storage::disk('public')->delete($car->image_location); // Remove the old file.
// Check if the old car image (if it existed) has been deleted.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': 'does not exist'));
$path = $request->image_location->store('images', 'public'); // save the new image.
// Check if the new file has been saved correctly.
Log::debug($path . (Storage::disk('public')
->exists($path)? ' exists': 'does not exist'));
$car->image_location = $path;
}
After uploading a new image, my storage/logs/laravel.log shows:
[2019-12-28 10:18:03] local.DEBUG: File has been found in request.
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif exists
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif does not exist
[2019-12-28 10:18:03] local.DEBUG: images/s9RtTdFSv0Is8AgxDWX5c09zG8SyU987RVeC0di5.gif exists
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'];
}
}
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'.