Laravel get uploaded image on CKEDITOR - php

when i use from ckeditor to upload image and attach that on post my upload image function in controller work fine without any problem, but when i want to return uploaded image to that, ckeditor can't get that, for example this is my code:
Controller:
public function uploadImageContent()
{
$this->validate(request(), [
'upload' => 'mimes:jpeg,jpg,gif,png'
]);
$file = request()->file('upload');
$filename = $file->getClientOriginalName();
$year = Carbon::now()->year;
$imagePath = "/uploads/post_images/{$year}/";
if (file_exists(public_path($imagePath) . $filename)) {
$filename = Carbon::now()->timestamp . '.' . $filename;
}
$file->move(public_path() . $imagePath, $filename);
$url = $imagePath . $filename;
return "<script>window.parent.CKEDITOR.tools.callFunction(1,'{$url}','')</script>";
}
this function work fine and i dont get any error on console or network
return "<script>window.parent.CKEDITOR.tools.callFunction(1,'{$url}','')</script>";
should be return path, but dont work.
view:
<script>
$(function () {
CKEDITOR.replace('description', {
height: '200px',
extraPlugins: 'forms',
filebrowserUploadUrl:'/dashboard/administrator/attachImage',
filebrowserImageUploadUrl:'/dashboard/administrator/attachImage'
});
});
</script>
route:
Route::group(['namespace' => 'Dashboard', 'prefix' => 'dashboard'], function () {
$this->group(['prefix' => 'administrator'], function () {
...
$this->post('/attachImage', 'ContentsController#attachImage');
...
});
ContentsController:
class ContentsController extends Controller
{
...
public function attachImage()
{
$this->uploadImageContent(request()->all());
}
}

Your code did not work for me. What I observed is, you are not embedding the CKEditorFuncNum (which server receives as POST variable) at the place of 1 as the first parameter to callFunction(). I replaced the 1 with $request->CKEditorFuncNum and then I used return statement instead of echo and it all works.
Here's your code:
echo "<script>window.parent.CKEDITOR.tools.callFunction(1,'{$url}','')</script>";
and
Here's my code:
return "<script>window.parent.CKEDITOR.tools.callFunction('{$request->CKEditorFuncNum}','{$url}','')</script>";
I'm on Laravel 5.8
Hope it helps others.

using echo instead of return resolve my problem:
echo "<script>window.parent.CKEDITOR.tools.callFunction(1,'{$url}','')</script>";
i have this issue on laravel 5.5

Related

how to delete multiple records that involve images in laravel

Please guys any idea how to delete multiple records that involve images. i do not know any approach that i can use. i have tried a lot.this is the what i have tried below.Pls help me guys i really need your help.Thanks in advance
please this is the code below
public function multipleUserDelete(Request $request,$id, $post_image){
if ($request->isMethod("post")) {
$data=$request->all();
//$del_user = $request->del_user;
// $ids=$del_user[];
//foreach(session('posts') as $session){
//foreach(session('products') as $postDelete){
$postDeletes=Post::where(['id'=> $id])
->where('post_image', $post_image)
->get();
foreach ($postDeletes as $postDelete) {
# code...
// $postDeletes=Post::where(['id'=> $id])->get();
//}
$large_image_paths='images/backend_image/admin_users/small/';
$medium_image_paths='images/backend_image/admin_users/medium/';
$small_image_paths='images/backend_image/admin_users/large/';
//Delete Image permenently from product table begins
//Delete Large image if not exist
if(file_exists($large_image_paths. $postDelete->post_image)){
unlink($large_image_paths. $postDelete->post_image);
}
//Delete Large image if not exist
if(file_exists($small_image_paths. $postDelete->post_image)){
unlink($small_image_paths. $postDelete->post_image);
}
//Delete Medium image if not exist
if(file_exists($medium_image_paths. $postDelete->post_image)){
unlink($medium_image_paths. $postDelete->post_image);
}
}
//$del_id=$request->input('del_feedback');
Post::whereIn('id', $data['del_user'])->delete();
return redirect()->back()->with("flash_message_success","you Successfully Deleted The Selected Users(s)");
}
Not tested, but I think something like this should work fine.
$image_path = "/images/"; // Value is not URL but directory file path
Post::where(['id'=> $id])
->where(function($query){
if(File::exists($image_path . $post_image)) {
File::delete($image_path . $post_image);
}
$query->where('post_image', $post_image)
})
->delete();
In general, the path issue should probably be
absolute.
See How to delete file from public folder in laravel 5.1
I don't know in Laravel 6, but it should work.
i.e. using File :: delete ()
Add the folder that contains your image to your config/filesystems.php files:
'disks' => [
'local' => [
'driver' => 'local',
'root' => base_path('app'),
],
//Above bit should already be there. So add this....
'some-image-path' => [
'driver' => 'local',
'root' => base_path("wherever/your/directory/is/from/root/"),
],
You would then use it like this:
$myImage = 'some-image.png';
Storage::disk('some-image-path')->delete($myImage);
public function multipleUserDelete(Request $request,$id, $post_image){
if ($request->isMethod("post")) {
$data=$request->all();
$postDeletes=Post::where(['id'=> $id])
->where('post_image', $post_image)
->get();
$img_array = array();
foreach ($postDeletes as $postDelete) {
$large_image_paths='images/backend_image/admin_users/small/';
$medium_image_paths='images/backend_image/admin_users/medium/';
$small_image_paths='images/backend_image/admin_users/large/';
$img='';
if(file_exists(public_path($large_image_paths. $postDelete->post_image))){
$img = $large_image_paths. $postDelete->post_image;
}
if(file_exists(public_path($small_image_paths. $postDelete->post_image))){
$img = $small_image_paths. $postDelete->post_image;
}
if(file_exists(public_path($medium_image_paths. $postDelete->post_image))){
$img = $medium_image_paths. $postDelete->post_image;
}
array_push($img_array,$img);
}
\File::delete($img_array);
Post::whereIn('id', $data['del_user'])->delete();
return redirect()->back()->with("flash_message_success","you Successfully Deleted The Selected Users(s)");
}

October CMS Routing

I'm trying to configure routes in my OctoberCMS app. I configure routes in Plugin.php file of my plugin.
At the moment my code:
public function boot()
{
Validator::extend('numeric_for_repeater', function($attribute, $value, $parameters) {
foreach ($value as $v)
{
$validator = Validator::make(
$v,
[
'stock_quantity' => 'sometimes|numeric',
'stock_votes_quantity' => 'sometimes|numeric',
'value' => 'sometimes|numeric',
],
$parameters
);
if ($validator->fails())
return false;
}
return true;
});
\Route::get('/oferty/{id}', function ($id = null) {
$theme = Theme::getActiveTheme();
$path = \Config::get('cms.themesPath', '/themes').'/'.$theme->getDirName();
$this->assetPath = $path;
$offer = new Offer();
return \View::make(self::MAMF_PAGE_DIR . 'oferta.htm', ['offer' => $offer->getOfferById($id)]);
});
}
but I got an error:
View [.var.www.plugins.mamf.mamf2017..........themes.mamf2017.pages.oferta.htm] not found. because by default October expects views files in plugin directory.
How can I render view outside of plugin dir, for ex in themes path like this app/themes/mamf2017/pages/oferta.htm
I guess self::MAMF_PAGE_DIR is full base path your application. for example like
/var/www/vhosts/octdev/themes/responsiv-flat/
In short \View::make need absolute path from root
now it will try to look file with configured extensions for october-cms its .htm. others are .blade and .htm.blade etc ..
so in your case (view)file name is 'oferta.htm' that .(dot) is translated to '/' path separator so just don't use it and just use 'oferta' so it will check all possible values in pages directory
oferta.htm
oferta.blade
oferta.htm.balde
this adding .htm is automatic thing so you just need to provide name of view then it will find and work automatically
\Route::get('/oferty/{id}', function ($id = null) {
$theme = \Cms\Classes\Theme::getActiveTheme();
$path = \Config::get('cms.themesPath', '/themes').'/'.$theme->getDirName();
$this->assetPath = $path;
$offer = new Offer();
return \View::make(base_path() . $path . '/pages/' . 'oferta', ['offer' => $offer->getOfferById($id)]);
});
this is tested and working fine hope this will help you.
if its not working please comment.

The requested URL was not found on this server but works local

I have a Laravel setup where I can add files and remove them. Now when I try to remove icons on my site on the server I get
Not Found
The requested URL /icons/24 was not found on this server.
Uploading the files and retrieving the files works. When I test it locally it works. And I do it the exact same way as with images, video files and audio files, and those all work on the server.
To debug it I also added the show() function in the controller, and that one also gives the same problem. What is going on?
routes/web.php: (partially)
Route::get('iconFile/{id}','IconController#iconFile');
Route::get('imageFile/{id}','ImageController#imageFile');
Route::get('audioFile/{id}','AudioController#audioFile');
Route::get('videoFile/{id}','VideoController#videoFile');
Route::get('signlanguageFile/{id}','SignlanguageController#signlanguageFile');
Route::group(['middleware' => ['auth']], function() {
Route::post('image-upload-with-validation',['as'=>'postimage','uses'=>'ImageController#postImage']);
Route::post('icon-upload-with-validation',['as'=>'posticon','uses'=>'IconController#postIcon']);
Route::resource('texts', 'TextController');
Route::resource('icons', 'IconController');
Route::resource('images', 'ImageController');
Route::resource('videos', 'VideoController');
Route::resource('signlanguages', 'SignlanguageController');
Route::resource('audios', 'AudioController');
});
IconController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Icon;
use Storage;
class IconController extends Controller
{
public function iconFile($id)
{
$icon = Icon::find($id);
$contents = Storage::disk('local')->get('uploads/icons/'.$icon->file);
$response = Response($contents);
$response->header('Content-Type', 'icon');
return $response;
}
public function show($id)
{
$icon = Icon::find($id);
$data = [
'icon' => $icon
];
echo $icon;
//return view('icon', $data);
}
public function postIcon(Request $request)
{
$this->validate($request, [
'icon_file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
]);
$iconName = time().'.'.$request->icon_file->getClientOriginalExtension();
$request->icon_file->move(storage_path('app/uploads/icons'), $iconName);
$icon = new Icon;
$icon->parent_id = $request->parent_id;
$icon->file = $iconName;
$icon->save();
return back()
->with('success','You have successfully uploaded an icon.')
->with('icon',$iconName);
}
public function destroy($id)
{
$icon = Icon::find($id);
$section_id = $icon->parent_id;
Storage::delete('uploads/icons/'.$icon->file);
$icon->delete();
return redirect('/section/'.$section_id)->with('success','Icon deleted.');
}
}
Update:
i tried replacing the resource route to Route::resource('iconz', 'IconController'); (with a z) and then it works! Changing it back to "icons" makes it stop working again. Could icons be some kind of reserved word?
Also tried php artisan route:clear which didn't help.

Laravel 5.1 And Dropzone.JS - Not Validating Image File

I am in Laravel 5.1 and am trying to use Dropzone.JS to handle uploading images and videos to my website. It is a very exciting process but unfortunately I am stuck currently and need help.
My routes.php:
Route::post('upload_video', ['as' => 'upload-post', 'uses' =>'ImageController#postUpload']);
My view from which I am sending the dropzone.js request:
<form action="/upload_video" enctype="multipart/form-data" class="dropzone needsclick dz-clickable" id="upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="dz-message needsclick">
Drop files here or click to upload.<br>
</div>
</form>
<script>
Dropzone.options.upload= {
url: "http://example.com/upload_video",
paramName: "file",// The name that will be used to transfer the file
maxFilesize: 20,
autoProccessQueue: false,
uploadMultiple: true,
addRemoveLinks: false,
parallelUploads: 10,
init: function() {
// this.on("successmultiple", function(file, serverresponse) { window.location.href="http://example.com/your_awesome_profile"; });
}
};
</script>
My Image Controller:
<?php
namespace App\Http\Controllers;
use App\Logic\Image\ImageRepository;
use Illuminate\Support\Facades\Input;
class ImageController extends Controller
{
protected $image;
public function __construct(ImageRepository $imageRepository)
{
$this->image = $imageRepository;
}
public function getUpload()
{
return view('pages.upload');
}
public function postUpload()
{
$photo = Input::all();
$response = $this->image->upload($photo);
return $response;
}
My Image Repository:
<?php
namespace App\Logic\Image;
use Auth;
use App\Models\Image;
use App\Models\Video;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
class ImageRepository
{
public function upload( $form_data )
{
//return dd($form_data);
$destinationPath = public_path().'/images/';
$validator = Validator::make($form_data, Image::$rules, Image::$messages);
if ($validator->fails()) {
//**FAILS HERE BUT IS AN IMAGE**
$validator = Validator::make($form_data, Video::$rules, Video::$messages);
}
else{
$photo = $form_data['file'];
$file = $photo->getClientOriginalName();
$filename = pathinfo($file, PATHINFO_FILENAME);
$extension = pathinfo($file, PATHINFO_EXTENSION);
$filename2 = $this->sanitize($filename);
$allowed_filename = $this->createUniqueFilename( $filename2, $extension );
$filenameExt = $allowed_filename . "." . $extension;
$uploadSuccess = $photo->move($destinationPath, $filenameExt);
if( !$uploadSuccess) {
return Response::json([
'error' => true,
'message' => 'Server error while uploading',
'code' => 500
], 500);
}
else{
$sessionImage = new Image;
$sessionImage->user_id = Auth::user()->id;
$sessionImage->name = $filename;
$sessionImage->url = $filenameExt;
list($width, $height) = getimagesize(public_path().'/images/' . $filenameExt);
$sessionImage->width = $width;
$sessionImage->height = $height;
$sessionImage->save();
return;
}
My problem is that, when I upload a .jpg I am being told that it is not a proper file type, even though my validation rules accept a .jpg. I'm not sure what I'm doing wrong, as the validator is failing on the line indicated in my Image Repository. Why does it fail there? At first I thought it was because return dd($form_data); yeilds an array but apparently that is what the validator wants, not a foreach for each file? I'm very confused, please assist and I can provide more code if needed, this is just excerpts.
Update: When I comment out my script in my view, the functionality seems to work perfectly in that images are being uploaded to my server and I can see this happening, but why when I set some options on the dropzone does it suddenly break? Any ideas?
The problem was on the client side. To be able to set options on the Dropzone.js properly, you want to disable autodiscover and set it up programmatically, like so:
Dropzone.autoDiscover = false;
After that, carry on, like so:
$("#upload").dropzone({
url: "http://examle.com/upload_video",
clickable: true,
uploadmultipe:true,
maxFilesize: 20,
init: function() {
this.on("queuecomplete", function(file, serverresponse) { window.location.href="http://example.com/your_awesome_profile"; });
}
});

blueimp/jQuery-File-Upload with Laravel How to integrate?

Trying to build my upload images part of my site and wanted to use blueimp/jQuery-File-Upload instead of hardcoding everything from scratch. However I am new too all that, could you tell me HOW to integrate that plugin with my Laravel structure ?
Where do I put all the files ? In vendors folder ? Or should I split all the folders and put their js folder in mine etc???
If you know a tutorial it is even better...
Couldn't find anything good with google.
Thanks
You can try this code I'm posting to help others.
The first step is to define the upload page and upload handling Routes, like this:
Route::get('image_', function() {
return View::make('image.upload-form');
});
Route::post('image_updade', 'ImageController#postUpload');
Make your image.upload-form view something like this (I'm using simple HTML, not a Blade template):
<?php echo Form::open(array('url' => 'image_updade', 'files' => true, 'id' => 'myForm')) ?>
Name: <input type='file' name='image' id='myFile'/>
<br/>
Comment: <textarea name='comment'></textarea>
<br/>
<input type='submit' value='Submit Comment' />
<?php echo Form::close() ?>
Now you need to add the JavaScript files in that view page's <HEAD> tag:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js'></script>
<script src='http://malsup.github.com/jquery.form.js'></script>
<script>
// Wait for the DOM to be loaded
$(document).ready(function() {
// Bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert('Thank you for your comment!');
});
$('#myFile').change(function() {
$('#myForm').submit();
});
});
</script>
Finally, here's a simple example of code for the ImageController#postUpload controller to get the uploaded file, and move it to a destination folder:
<?php
class ImageController extends BaseController {
public function getUploadForm() {
return View::make('image/upload-form');
}
public function postUpload() {
$file = Input::file('image');
$input = array('image' => $file);
$rules = array( 'image' => 'image');
$validator = Validator::make($input, $rules);
if ( $validator->fails() ){
return Response::json(['success' => false, 'errors' => $validator->getMessageBag()->toArray()]);
}
else {
$destinationPath = 'files/';
$filename = $file->getClientOriginalName();
Input::file('image')->move($destinationPath, $filename);
return Response::json(['success' => true, 'file' => asset($destinationPath.$filename)]);
}
}
}

Categories