i am new using codigniter. i am trying to display images from the mysql database by sending them to the database using a create page where you can type in a title, some info and select an image, everything displays after creating a project except for the image. once i open phpmyadmin it shows that there is data for the image but it looks like it's only MetaData and not the actual image itself. i have been stuck on this for a couple of days now so i hope you guys could help me out!
create function in The Controller (edited):
public function create(){
$model = new ProjectModel();
$file = $this->request->getFile('image');
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'info' => 'required',
'image' => 'uploaded[image]',
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
$tempfile = $file->getTempName(),
$imgdata = file_get_contents($tempfile),
]);
var_dump($imgdata);
#echo view('project/success');
}
else
{
echo view('site/create');
}
}
My Model
namespace App\Models;
use CodeIgniter\Model;
class ProjectModel extends Model
{
protected $table = 'projects';
protected $allowedFields = ['title', 'slug', 'info', 'image'];
public function getProjects($slug = false)
{
if ($slug === false)
{
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
this is the file that creates a div element once you press the create button
<?php if (! empty($projects) && is_array($projects)) : ?>
<?php foreach ($projects as $project_item): ?>
<div class="project-box" href="/projects/<?= esc($project_item['slug'], 'url') ?>">
<?php echo '<img class="project-image" src="data:image/jpeg;base64,'.base64_encode($project_item['image']).'" alt="image" ">'?>
<p class="project-name"><?=esc($project_item['title'])?></p>
<div class="bottom-border">
<p class="project-creator"><i class="far fa-user-circle"></i> <?=esc($project_item['creator'])?></p>
<div class="statistics">
<p class="project-likes"><i class="fas fa-heart"></i> <?=esc($project_item['likes'])?></p>
<p class="project-views"><i class="far fa-eye"></i> <?=esc($project_item['views'])?></p>
</div>
</div>
</div>
<?php endforeach; ?>
<?php else : ?>
<h3>No Projects</h3>
<?php endif ?>
this is the create file in which you can create a project
<div class="parent">
<?= \Config\Services::validation()->listErrors() ?>
<form action="/site/create" method="post">
<h1>Create Project</h1>
<?= csrf_field() ?>
<div class="form-group">
<input class="ph-title" type="input" name="title" placeholder="Title" /><br/>
</div>
<div class="grow-wrap">
<textarea class="ph-info" name="info" placeholder="Type in project info"></textarea>
</div>
<!-- <div class="file-input">
<label for="file">
Select file
<p class="file-name"></p>
</label>
</div> -->
<input class="file-btn" type="file" name="image" value=""/><br/>
<input class="create-btn" type="submit" name="submit" value="Create Project"/>
</form>
</div>
What am i doing wrong?
There are a few things wrong here. First off, your form is set for image uploading, but needs the enctype added to the form tag so that your backend PHP can recieve the $_FILES object
<form action="/site/create" method="post" enctype="multipart/form-data">
Remove the value="" from the input...
<input class="file-btn" type="file" name="image" />
Now you're ready to receive a file - see https://codeigniter4.github.io/userguide/libraries/uploaded_files.html
Your validation should be altered
$this->validate([
//... your other validations...
'image' => 'uploaded[image]' // instead of required
]);
If you want to store the image on your server and then record the name of the image in the database to retrieve later:
$imageDirectory="/path/to/where/you/store/images";
$imageName = $file->getRandomName();
$path = $this->request->getFile('image')->store($imageDirectory, $imageName);
// path is now the full path to the image on your server.
if you want to store the image BLOB data instead (like your example):
$tempfile = $file->getTempName();
$imgdata = file_get_contents($tempfile);
Then your insert would look like this...
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'info' => $this->request->getPost('info'),
'image' => $imgdata,
]);
Related
I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}
I m working on showing a post, when i post data with the image then my data stored in DB (image is also storing into destination folder) but not showing on the browser, here is the code of the page(index.blade.php) on which m trying to show post:
#extends('layouts.app')
#section('content')
<form method="POST" action="{{url('posts')}}" enctype="multipart/form-data">
<!--#if(session('message'))
{{session('messgae')}}
#endif-->
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
{{csrf_field()}}
Name:- <input type="text" name="title" value="{{old('title')}}">
Text:- <textarea name="body">value="{{old('body')}"></textarea>
Upload File:- <input type="file" name="thumbnail" value="{{old('thumbnail')}}">
<input type="submit" value="submit">
</form>
#endsection
this is post controller
public function store(Request $request)
{
if($request->hasFile('thumbnail') && $request->thumbnail->isValid())
{
$extension = $request->thumbnail->extension();
$filename = time()."_.".$extension;
$request->thumbnail->move(public_path('images'), $filename);
}
else
{
$filename = 'code.png';
}
\App\Post::create([
'title' => $request->title,
'body' => $request->body,
'thumbnail' => $filename,
]);
return redirect('posts');
}
I found a mistake in your code
#foreach($posts as post)
use
#foreach($posts as $post)
I am trying to implement a image upload with other form elements with dropzone.js in laravel. So far I've managed to display the drag and drop image upload view with other form elements. And also get POST details from the submitted form. But when dropzone is passing the uploaded image to the database data save function it encode image with base64. I think I've managed to get the file extension also. And when I submit the button it gives me this error "Call to a member function move() on string" . Please put me in the right direction.
Here is the Form
<form class="form-horizontal" action="{{ route('save-slider-content') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderTitle" id="sliderTitle" placeholder="Title of the post goes here">
</div>
</div>
<input type="hidden" name="date" id="date" value="<?php echo date("d-m-Y"); ?>">
<div class="form-group">
<label for="image" class="col-sm-2 control-label">Image</label>
<input hidden id="file" name="file"/>
<div class="col-sm-10">
<div class="dropzone needsclick dz-clickable" id="fileUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Link</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderLink" id="sliderLink" placeholder="Provide a link">
</div>
</div>
</div><br>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
<!-- /.box-footer -->
</form>
Here is the dropzone configuration
<script type="text/javascript">
Dropzone.options.fileUpload = {
url: "save-slider-content",
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
</script>
Route
Route::post('store-slider-content', [ 'as' => 'save-slider-content', 'uses' => 'SliderContent#save_slider_data']);
save_slider_data function in Controller
public function save_slider_data(Request $request)
{
$slider = new Slider;
$slider->title = $request->sliderTitle;
$slider->title_sin = $request->sliderTitleSin;
$slider->date = $request->date;
$slider->link = $request->sliderLink;
$file = $request->file;;
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = time().'.'.$mime_type;
$image_data->move(public_path('slider_uploads'), $imageName);
return response()->json(['success'=>$imageName]);
$slider->img_url = $imageName;
$slider->save();
}
Edited to include the logic for either Symfony\Component\HttpFoundation\File\File or Illuminate\Support\Facades\File (Illuminate\Filesystem\Filesystem)
move is a method of a File object, but $image_data is just a string. So one thing you could do is write the decoded image to a temp file, instantiate a File of it, and move it, like
//... your code ...
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
// ... and then:
//grab a new tmp file
$tmpFilePath=sys_get_temp_dir().'/'.uniqid();
//write the image to it
file_put_contents($tmpFilePath, $image_data);
//move it.
//give it a name
$imageName = time().'.'.str_replace("image/","",$mime_type);
//if using Symfony\Component\HttpFoundation\File\File;
//get an instance of File from the temp file and call ->move on it
$tmpFile=new File($tmpFilePath);
$tmpFile->move(public_path('slider_uploads'), $imageName);
//or if using File facade
File::move($tmpFilePath, public_path("slider_uploads/$imageName"));
//...and then, back to your code...
$slider->img_url = $imageName;
$slider->save();
return response()->json(['success'=>$imageName]);
}
You can do this:
In config/filesystems.php, register a new disk slider_uploads
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'slider_uploads' => [
'driver' => 'local',
'root' => public_path('slider_uploads')
]
]
And then use your new disk in storing your image
$image_data = $request->file;
#list($type, $image_data ) = explode(';', $image_data );
#list(, $image_data ) = explode(',', $image_data );
if($image_data !=""){ // storing image in public/slider_uploads/ Folder
\Storage::disk('slider_uploads')->put($imageName, base64_decode($image_data ));
}
I have been getting this error while submiting a form using codeigniter. I need help even though I have been following the documentation.
I am using 2.x version of codeigniter
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Products::$input‐
Filename: core/Model.php
Line Number: 52
Fatal error: Call to undefined function post() in /opt/lampp/htdocs/gamingplace/application/models/product_model.php on line 63
This is the code in my model
//add new product
public function addProduct(){
$data = array(
'category_id' => $this->input‐>post('category_id'),
'title' => $this->input‐>post('title'),
'description' => $this->input‐>post('description'),
'price' => $this->input‐>post('price')
);
if($_FILES['image']['error'] == 0){
$data['image'] = $this->upload->file_name;
return $this->db->insert('products',$data);
}
}
}
This is the code in my controller
public function addProduct()
{
if($_FILES['image']['error'] == 0){
//setting image preferences
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'jpg|png|jpeg|PNG|JPEG|JPG';
$config['overwrite'] = false;
$config['quality'] = '100%';
$config['remove_spaces'] = true;
$config['max_size'] = '90';// in KB
$this->load->library('upload',$config);
echo $this->input->post('image');
if( ! $this->upload->do_upload('image'))
{
$this->session->set_flashdata('message_failed', $this->upload->display_errors('', ''));
redirect('dashboard');
}else{
//Image Resizing
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['maintain_ratio'] = FALSE;
$config['width'] = 311;
$config['height'] = 162;
$this->load->library('image_lib',$config);
if ( ! $this->image_lib->resize()){
$this->session->set_flashdata('message_failed', $this->image_lib->display_errors('', ''));
}
//calling a model an its method to add a new product to the database
if($this->product_model->addProduct()){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
}
}
}
}
And my view
<!-- Modal -->
<script src="<?php echo base_url(); ?>assets/js/validation.js" charset="utf-8"></script>
<div class="modal fade" id="addProduct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Product</h4> <em>if the product category is not in the select option,
go to add category link to add category before adding this product</em>
</div>
<div class="modal-body">
<?php echo validation_errors('<div class="alert alert-danger">','</div>') ?>
<form role= "form" action="<?php echo base_url()?>products/addProduct" method="post" name="form" onsubmit="return validate(this)" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" class="form-control" placeholder="Enter name of product" required>
</div>
<div class="form-group">
<label>Brief Description of Product</label>
<textarea name="description" rows="8" cols="80" class="form-control">
This is a brand made by Gucci Company. Made of cotton, bla bla bla
</textarea>
</div>
<label>Select Category</label>
<div class="form-group">
<select class="form-control" name="category_id">
<?php foreach (get_categories_h() as $popular): ?>
<option value="<?php echo$popular->id?>"><?php echo $popular->name ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Enter or choose price</label>
<input type="number" id="price" class="form-control" name="price_old" required>
</div>
<input type="hidden" name="price" class="form-control" id="mainPrice"required>
<div class="form-group">
<input type="file" name="image" id="image" class="form-control" required accept="image/*" onChange="validateImage(this.value)">
</div>
<button type="submit" name="submit" class=" form-control btn btn-success">Add</button>
</form>
</form>
</div>
</div>
</div>
</div>
I think you may have a few issues going on with your code, but let's first focus on your question/error you mentioned. In your controller function, you are not passing the post to the model. You need to do something like this in the controller:
$addProduct = $this->product_model->addProduct($_POST);
if($addProduct){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
In the model function, you need to first let the function know there is an incoming parameter, then adjust how you are assigning the fields to the data array.
public function addProduct($post){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"]
);
return $this->db->insert('products',$data);
}
After that, I noticed that you have some other FILES logic in your model. That will likely error out, too. I believe that is going to have to be done in the controller, not the model. Once you do the upload in the controller, you can pass the file name into the model as well.
$upload_data = $this->upload->data();
$addProduct = $this->product_model->addProduct($_POST, $upload_data['file_name']);
if($addProduct){
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
Then, adjust the model.
public function addProduct($post, $fileName){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"],
'image' => $fileName
);
return $this->db->insert('products',$data);
}
Hope this helps.
In laravel i am making an application that uploads a file and the user can download that same file.
But each time i click to upload i get this error.
FileNotFoundException in File.php line 37: The file
"H:\wamp64\tmp\phpF040.tmp" does not exist
my view code is this:
#extends('layouts.app')
#section('content')
#inject('Kala','App\Kala')
<div class="container">
<div class="row">
#include('common.errors')
<form action="/addkala" method="post" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" name="name">
<input type="text" name="details">
<input type="file" name="photo" id="photo" >
<button type="submit">submit</button>
</form>
</div>
</div>
#endsection
and my controller
public function addkalapost(Request $request)
{
$rules = [
'name' => 'required|max:255',
'details' => 'required',
'photo' => 'max:1024',
];
$v = Validator::make($request->all(), $rules);
if($v->fails()){
return redirect()->back()->withErrors($v->errors())->withInput($request->except('photo'));
} else {
$file = $request->file('photo');
$fileName = time().'_'.$request->name;
$destinationPath = public_path().'/uploads';
$file->move($destinationPath, $fileName);
$kala=new Kala;
$kala->name=$request->name;
return 1;
$kala->details=$request->details;
$kala->pic_name=$fileName;
$kala->save();
return redirect()->back()->with('message', 'The post successfully inserted.');
}
}
and i change the upload max size in php.ini to 1000M.
plz help
im confusing
I'll recommend you using filesystems for that by default the folder is storage/app you need to get file from there
if your file is located somewhere else you can make your own disk in config/filesystems e.g. 'myDisk' => [
'driver' => 'local',
'root' =>base_path('xyzFolder'),
],
and you can call it like
use Illuminate\Support\Facades\Storage;
$data = Storage::disk('myDisk')->get('myFile.txt');
this is obviously to get file and you can perform any other function by following laravel docs.