Image upload from front-end - php

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();
}

Related

Fetch image variable and display on input file

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");

How to associate files to post with Laravel 5.6

I am using Laravel for my web app and I want to associate files to my posts in indepent way with his own form, but I have some problems
My routes (I am using a auth control package, but actually I am admin):
Route::post('file', 'fileController#store')->name('file.store')
->middleware('permission:file.create');
Route::get('file', 'fileController#index')->name('file.index')
->middleware('permission:file.index');
Route::get('file/create/', 'fileController#create')->name('file.create')
->middleware('permission:file.create');
Route::put('file/{id}', 'fileController#update')->name('file.update')
->middleware('permission:file.edit');
Route::get('file/{id}', 'fileController#show')->name('file.show')
->middleware('permission:file.show');
Route::delete('file/{id}', 'fileController#destroy')->name('file.destroy')
->middleware('permission:file.destroy');
Route::get('file/{id}/edit', 'fileController#edit')->name('file.edit')
->middleware('permission:file.edit');
Route::get('download/{filename}', 'fileController#download')->name('file.download')
->middleware('permission:file.download');
My migration:
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('files_id')->unsigned();
$table->string('filenames');
$table->integer('fileable_id')->unsigned();
$table->string('fileable_type');
$table->timestamps();
});
My File Model:
class File extends Model
{
protected $fillable = [
'filenames', 'project_id'
];
public function user()
{
return $this->belongsTo(User::class);
}
My Project Model:
public function files()
{
return $this->morphMany(File::class, 'fileable')->whereNull('files_id');
}
My Controller to store:
class FileController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'filenames' => 'required',
'project_id' => 'required',
// 'filenames.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('filenames'))
{
foreach($request->file('filenames') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new File();
$file->filenames = $request->get('filenames');
$file->filenames= $name;
$file->user()->associate($request->user());
$project = Project::findOrFail($request->get('project_id'));
$project->files()->save($file);
$file->save();
return back();
}
public function download( $filename = '' ) {
// Check if file exists in storage directory
$file_path = public_path() . '/files/' . $filename;
if ( file_exists( $file_path ) ) {
// Send Download
return \Response::download( $file_path, $filename );
} else {
return back()->with('info', 'Archivo no existe en el servidor');
}
}
The Form in blade:
<form method="post" action="{{ route('file.store') }}" enctype="multipart/form-data">
<div class="input-group hdtuto control-group lst increment" >
<input type="file" name="filenames[]" class="myfrm form-control">
<input type="hidden" name="project_id" value="{{ $project->id }}" />
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="fldemo glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<button type="submit" class="btn btn-success" style="margin-top:10px">Submit</button>
</form>
Foreach to download files:
#foreach($project->files as $file)
<li>{{ $file->user->name }}: <a href="{{ url('/download/')}}/{{$file->filenames}}" download> {{$file->filenames}}</a></li>
#endforeach
I send files from Project Controll
The reason you are getting the first error message is because the Project with the id you get from Request is not found in the Database and returns null instead of an object. That would mean you are indeed calling files() method on null. To resolve this there are multiple steps.
1.) Make sure project_id is inside the Request at all times:
$this->validate($request, [
'filenames' => 'required',
'project_id' => 'required',
// 'filenames.*' => 'mimes:doc,pdf,docx,zip'
]);
2.) Make sure to check for project if it exists after retrieving it from database, this can be done in two ways.
a) You can either find the project or throw an Exception if it's not found:
$project = Project::findOrFail($request->get('project_id');`
b) You can check with a simple if statement if it does not exist and do something
$project = Project::find($request->get('project_id');
if (!$project) {
// Project not found in database
// Handle it
}

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;
}
}

How to update image using controller in laravel?

I want to update user image but it's not getting updated. I have used following controller for updating the image.. Can you suggest what's the mistake in controller function?
View part :
<div class="form-group">
<label>Image Upload</label>
<input type="file" name="image" id="image"><img src="{{ asset('public/images/' . $course->image) }}" width="200px"/></br>
</div>
Controller function :
public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
}
$data->course_code = $request['course_code'];
$data->course_title = $request['course_title'];
$data->course_credit = $request['course_credit'];
$data->save();
return redirect('course');
}
Did you checked file permission on 'images' directory? It needs to have write permission for uploading files.
The problem is this,
$data->image = $name;
You set the value but you don't save it anywhere. You must add a saving line.
$data->save();
Note that, calling update() only saves what you pass in as parameters, doesn't save what you set through the mutators.
See The mistake/ solution of the problem is first i need to store the update value and then save the new image. So I made some changes in controller and solved it..
Here is controller code:
public function update(Request $request, $id)
{
$data=Course::findOrFail($id);
$data->update($request->all());
if ($request->hasFile('image'))
{
$file = $request->file('image');
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$data->image = $name;
$file->move(public_path().'/images/', $name);
$data->save();
}
return redirect('course');
}

Call to a member function getClientOriginalExtension() on a non-object error

I am trying to edit/update my image upload but I am getting "Call to a member function getClientOriginalExtension() on a non-object" error. please help
My controller:
public function update(Request $request, $id)
{
$lnkupdate=Request::all();
$links=Links::findorFail($id);
$file = Input::file('image');
$random_name = str_random(8);
$destinationPath = 'albums/';
$extension = $file->getClientOriginalExtension();
$filename=$random_name.'_link_logo.'.$extension;
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
ConsularGen::update(array(
'name'=>Input::get('name'),
'link' => Input::get('link'),
'image' => $filename,
));
}
View:
{!!Form::model($links,['method'=>'PATCH','action'=>['LinksController#update',$links->id]])!!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="image">Select a logo</label>
{!!Form::file('image')!!}
</div>
<div class="form-goup">
{!!Form::label('name','Name')!!}
{!!Form::text('name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('link','Link')!!}
{!!Form::text('link',null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
<button type="submit" class="btnbtn-default">Add</button>
</div>
{!!Form::close()!!}
Route:
Route::patch('admin/links/{id}/update','LinksController#update');
Uploading files requires the html form to specify enctype="multipart/form-data". If you don't have this, the file will not be uploaded, Input::file('image') will return null, and you'll get the error you're seeing.
The Laravel Form builder will add this to your form if you tell it that it needs to handle files. Add 'files' => true to your array in the form:
{!! Form::model($links, ['method'=>'PATCH', 'files' => true, 'action'=>['LinksController#update', $links->id]]) !!}
Once this is fixed, you'll also get this error if you don't actually select a file to be uploaded. You should wrap your file handing inside a check to hasFile. Something like:
public function update(Request $request, $id)
{
$lnkupdate=Request::all();
if (Input::hasFile('image')) {
$links=Links::findorFail($id);
$file = Input::file('image');
$random_name = str_random(8);
$destinationPath = 'albums/';
$extension = $file->getClientOriginalExtension();
$filename=$random_name.'_link_logo.'.$extension;
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
ConsularGen::update(array(
'name'=>Input::get('name'),
'link' => Input::get('link'),
'image' => $filename,
));
} else {
echo 'no file uploaded. oops.';
}
}
Your file has not uploaded successfully.
you are trying to run getClientOriginalExtension() on a null file thats's why you are getting this error

Categories