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

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

Related

Laravel get uploaded image on CKEDITOR

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

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

Yii PHP file uploader overwriting on update

I have a basic form in PHP framework Yii, the action to create works fine, however, when i update the record (for example if i'm not changing the file upload, but another field), it overwrites the file upload and blanks it, can anyone assist me? I've tried all the validation I can think of around the controller items, but no matter what i add it still blanks it on update.
Here's the view code
<?php $form=$this->beginWidget('booster.widgets.TbActiveForm', array(
'id'=>'company-form',
'enableAjaxValidation'=>false,
'method' => 'post',
'type' => 'horizontal',
'htmlOptions' => array(
'enctype' => 'multipart/form-data'
)
));
echo $form->textFieldGroup($model,'name',array('class'=>'col-md-5','maxlength'=>75));
echo $form->fileFieldGroup($model, 'logo',
array(
'wrapperHtmlOptions' => array(
'class' => 'col-md-9',
),
'hint' => 'You can only upload jpg, png, gif\'s – max upload filesize is 1.5mb. Square images are advised.<br/>In certain browsers, you can also drag \' drop files into the dropzone.',
)
);
if($model->isNewRecord!='1'){ ?>
<div class="row">
<label class="col-md-3 control-label" style="padding-top: 25px;">Company image</label>
<div class="col-md-6">
<?php echo CHtml::image(Yii::app()->request->baseUrl.'/images/portraits/company/'.$model->logo,"logo",array("class"=>"img-polaroid placeholder")); ?>
</div>
</div>
<?php } ?>
And this is my actionUpdate function in Controller
public function actionUpdate($id)
{
$model=$this->loadModel($id);
if(isset($_POST['Company']))
{
$model->attributes=$_POST['Company'];
$uploadedFile=CUploadedFile::getInstance($model,'logo');
if (is_object($uploadedFile) && get_class($uploadedFile)==='CUploadedFile'){
if(!$uploadedFile == null){
$rnd = rand(0,9999);
$filename_preg1 = preg_replace("/[^a-zA-Z0-9.]/", '', "{$uploadedFile}");
$fileName = "{$rnd}-{$filename_preg1}";
$company = $model->name;
$model->logo = $fileName;
}
if($model->save()){
if(!empty($uploadedFile)){
$fullPath = Yii::app()->basePath . '/../images/portraits/company/' . $fileName;
$uploadedFile->saveAs($fullPath);
}
$this->redirect(array('view','id'=>$model->company_id));
}
}
if($model->save()){
$this->redirect(array('view','id'=>$model->company_id));
}
}
$this->render('update',array(
'model'=>$model,
));
}
Can anyone see where i'm going wrong?
UPDATE
Thanks SiZE, the code you gave me worked in one form and not in the other, the one it didn't work in has validation in the model rules
array('logo', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
This only works with the allowEmpty param here as it's not a required field, however, with the rule in place in the model, it still blanks the file field regardless, anyone have any more thoughts?
CActiveForm calls CHtml::activeFileField method wich generates empty hidden field to correctly work with model's rules.
You can try this:
$model=$this->loadModel($id);
$original_logo = $model->logo;
if(isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$logo = CUploadedFile::getInstance($model, 'logo');
$model->logo = $logo !== null ? $logo->getName() : $original_logo;
if ($model->save()) {
if ($logo !== null) {
$logo->saveAs(/* specify path with file name here */);
}
$this->redirect(array('view','id'=>$model->company_id));
}
}

Yii file field posting empty values

I am a newbie in Yii, and I am trying to make an upload form in Yii, Please i need help.
Once the form post data to the controller every other post value is posted except for the file value.
i even tried checking for Errors with var_dump($model->image); and it returned this Error string '' (length=0) specifying an empty string like an image wasn't even posted at all.
This is my controller
class TestController extends Controller
{
public function actionIndex()
{
$model=new Test;
if(isset($_POST['Test']))
{
$model->attributes=$_POST['Test'];
if($model->save()){
var_dump($model->getErrors());
if ($model->image){
var_dump($model->image);
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = date("Y_m_d_H_i_s").$uploadedFile;
$model->image = $fileName;
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/imagefolder/'.$fileName);
}
}
}
}
}
}
And this is my View
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'test-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation'=>false,
)); ?>
<?php echo CHtml::activeFileField($model,'image',array('id'=>'primaryupload')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'UPLOAD' : 'UPLOAD',array('id'=>'submit','class'=>'btn')); ?>
<?php $this->endWidget(); ?>
Any help will be appreciated. Because i am really frusrated at this point.
If you are only new to Yii and not in PHP, than you may know that uploaded files goes via $_FILES global variable and not via $_POST global variable. So to get uploaded file, you use
$uploadedFile = CUploadedFile::getInstance($model, 'image');
So your final code looks like this:
$post = Yii::app()->request->getPost('Test');
if ($post) {
$model->attributes = $post;
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if ($uploadedFile) {
$imageName = date("Y_m_d_H_i_s").$uploadedFile->name;
$model->image = $imageName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/imagefolder/'.$imageName );
}
}
I think you should use $_FILES['image'] instead of $model->image.
As an option, you can "hardcode" file attribute in your form. Just:
<input type="file" id="yourid" name="yourname" />
Then in YourController, where you are parsing your POST data you could directly access to $_FILES['yourname'].
Not an elegant way, but simple and fast.
P.S.: if you are using $this->beginWidget in your view, then you should add to parameters
$this->beginWidget('CActiveForm', array(
...
'htmlOptions'=>array(
'enctype'=>'multipart/form-data'
),
));

PHP Laravel Framework Uploading Image Form Processing

I'm trying to learn to an process image form that uploads images to a database and lets users view the image on the website, this is done using Laravel 4. I must have some sort of bug, because the view doesn't have any errors, but when I select an image to upload and hit the "save" button on my form, nothing happens other than it looks like the form has been refreshed because the file is gone.
Routes
// This is for the get event of the index page
Route::get('/', array(
'as' => 'index_page',
'uses' => 'ImageController#getIndex'
));
// This is for the post event of the index page
Route::post('/', array(
'as' => 'index_page_post',
'before' => 'csrf',
'uses' => 'ImageController#postIndex'
));
ImageController.php
class ImageController extends BaseController {
public function getIndex()
{
// Let's first load the form view
return View::make('tpl.index');
}
public function postIndex()
{
// Let's validate the form first with the rules which are set at the model
$input = Input::all();
$rules = Photo::$upload_rules;
$validation = Validator::make($input, $rules);
// If the validation fails, we redirect the user to the index page, with errors
if ($validation->passes()) {
// If the validation passes, we upload the image to the database and process it
$image = Input::file('image');
// This is the original uploaded client name of the image
$filename = $image->getClientOriginalName();
// Because Symfony API does not provide filename
// without extension, we will be using raw PHP here
$filename = pathinfo($filename, PATHINFO_FILENAME);
// We should salt and make an url-friendly version of the file
$fullname = Str::slug(Str::random(8) . $filename) . '.' .
$image->getClientOriginalExtension();
// We upload the image first to the upload folder, then
// get make a thumbnail from the uploaded image
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
// If the file is now uploaded we show a success message
// otherwise, we show an error
if ($upload) {
// image is now uploaded, we first need to add column to the database
$insert_id = DB::table('photos')->insertGetId(
array(
'title' => Input::get('title'),
'image' => $fullname
)
);
// Now we redirect to the image's permalink
return Redirect::to(URL::to('snatch/'.$insert_id))
->with('success', 'Your image is uploaded successfully!');
}
else {
// Image cannot be uploaded
return Redirect::to('/')->withInput()
->with('error', 'Sorry, the image could not be uploaded.');
}
}
else {
return Redirect::to('/')
->withInput()
->withErrors($validation);
}
}
Image Model
class Photo extends Eloquent {
// the variable that sets the table name
protected $table = 'photos';
// the variable that sets the table name
protected $fillable = array('title', 'image');
// the timestamps enabled
public $timestamps = true;
// Rules of the image upload form
public static $upload_rules = array(
'title' => 'required|min:3',
'image' => 'required|image'
);
}
The view for the form
#extends('frontend_master')
#section('content')
{{ Form::open(array('url' => '/', 'files' => true )) }}
{{ Form::text('title', '', array(
'placeholder' => 'Please insert your title here')) }}
{{ Form::file('image') }}
{{ Form::submit('save', array('name' => 'send')) }}
{{ Form::close() }}
#stop
Let me know if you can find any bugs, I'm pretty sure something must be going wrong in my ImageController#postIndex
Thanks for any insights
2 things you need to check out.
1st off, once you updated your composer.json to include the Intervention/Image package. you should run composer dump-autoload to refresh the autoload file.
2ndly, there's a logical error in your controller.
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
should be
Image::make(Config::get('image.image_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
because you've already moved the image file to image_folder with the code below:
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Hope this helps.

Categories