Image in Laravel 5 is not working - php

I am working with image in Laravel 5. I use folklore package of Laravel 5. it works fine for store but shows problem while updating image.
ArticleController:
$article_to_update = $article->find($id);
$uploaded_image = $request->file('image_file');
$parameter = $request->all();
if (isset($uploaded_image))
{
$ext = $uploaded_image->getClientOriginalExtension();
$newImageName = $article_to_update->id . "." . $ext;
$uploaded_image->move(
base_path() . '/public/uploads/article/', $newImageName
);
Image::make(base_path() . '/public/uploads/article/' . $newImageName, array(
'width' => 170,
'height' => 120,
))->save(base_path() . '/public/uploads/article/' . $newImageName);
$parameter = $request->all();
$parameter['image'] = $newImageName;
unset($parameter['image_file']);
$article_to_update->update($parameter);
} else
{
$article_to_update->update($parameter);
}
Session::flash('message', 'The article was successfully edited!.');
Session::flash('flash_type', 'alert-success');
return redirect('articles');
}
Edit.blade.php:
<div class="form-group">
<label><b>IMAGE</b></label>
{!! Form::file('image_file',null,array('class'=>'form-control','id'=>'file_uploader')) !!}
{!! Form::text('image',null,array('class'=>'form-control','id'=> 'file-name')) !!}
</div>
Model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use \App\Auth;
/**
* Class Article
* #package App
*/
class Article extends Model {
/**
* #var array
*/
protected $guarded = [];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags()
{
return $this->belongsToMany('App\Tag');
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo('App\Category');
}
}
problem shows when i put a image too in the field..
Column not found: 1054 Unknown column 'image_file' in 'field list'
(SQL: update `articles` set `updated_at` = 2015-08-20 07:15:14,
`image_file` = afc-logo.gif where `id` = 457)
Anyone help?

The above code was not working because in edit form, encrypt/multipart is not used for image or any file..
so I used file=true that solved my problem..
{!! Form::model($article,['method' => 'PATCH','route'=> ['articles.update',$article->id],'files' => true]) !!}
This solves the whole updating image problem...

Related

Laravel : Expected type 'object'. Found 'array'. intelephense(1006). (VSCode) [closed]

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 months ago.
Improve this question
I am submitting a form thorugh ajax, form values are saving in the database and errors are showing without page reload, which is a good thing. As I am a beginner so i cannot make sense of this error. This error is not disturbing or impacting the flow of the application in any way. Thanks.
**Here's the error's image: **
**Here's the code of the controller: **
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Products;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;
class ProductController extends Controller
{
//Search Products
public function search(Request $request)
{
$products = Products::where('name','like', '%'.$request->search.'%')
->orWhere('id','like', '%'.$request->search.'%')->get();
$output = "";
foreach($products as $products)
{
$output.=
'<tr class="border-bottom border-dark p-3">
<td>'.$products->name.'</td>
<td>'.$products->s_description.'</td>
<td>'.$products->l_description.'</td>
<td class="align-center p-5"><img class="img-fluid" src='.asset('images')."/".$products->image_src.'></td>
<td>'.$products->category.'</td>
<td>'.$products->quantity.'</td>
<td>'.$products->price.'</td>
<td>'.'
<form action='.route('delete_product', $products->id).' method="POST" id="deleteBtn">
z
<input type="hidden" name="_method" value="delete">
<button class="btn btn-danger" type="submit">'.'Delete</button>
</form>
'.'
</td>
</tr>
';
}
return response($output);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function viewProducts()
{
$p_details = Products::all();
return view('admin.products.view_products', compact('p_details'));
}
public function productVerify(Request $request)
{
$val = $request->validate
(
[
'name' => 'required',
's_description' => 'required',
'l_description' => 'required',
'image_src' => 'required|mimes:jpg,png,jpeg',
'category' => 'required',
'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
'price' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
],
[
'required' => 'The :attribute field is required',
'mimes' => 'Image should be a JPG, JPEG, or PNG',
'integer' => 'The :attribute field should be an integer.',
]
);
if ($val)
{
return response()->json(['errors'=>($val)->errors()->all()]);
}
else
{
// return redirect()->to('view_products')->with('success','Product added successfully');
return response()->json(['errors'=>'Product added successfully, head to view products to inspect it. Thanks!']);
}
}
//Uploading Images
public function validImg(Request $request)
{
if ($request->hasFile('image_src'))
{
$filename = $request->file('image_src');
$filename->getClientOriginalName();
$filename = time().$filename->getClientOriginalName();
$destinationPath = base_path("/public/images");
$request->file('image_src')->move($destinationPath, $filename);
$data['image_src'] = $filename;
}
return $data['image_src'];
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.products.add_products');
}
//Creating and Adding Products
public function createProduct(Request $request)
{
//Product Validation
$validation = $this->productVerify($request);
$data = $request->all();
$image_src = $this->validImg($request);
Products::create
([
'name' => $data['name'],
's_description' => $data['s_description'],
'l_description' => $data['l_description'],
'category' => $data['category'],
'quantity' => $data['quantity'],
'price' => $data['price'],
'image_src' => $image_src
]);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$product_edit = Products::findOrFail($id);
return view('admin.products.edit_products', compact('product_edit'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//Product Validation
$validatedData = $this->productValidation($request);
$this->validImg($request);
Products::whereId($id)->update($validatedData);
return redirect('view_products')->with('success', 'Product details successfully updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$products = Products::findOrFail($id);
$destinationPath = base_path("/public/images").'/'.$products->image_src;
if(File::exists($destinationPath))
{
File::delete($destinationPath); //for deleting only file try this
$products->delete(); //for deleting record and file try both
}
// $products->delete();
return redirect('view_products')->with('error', 'Product successfully deleted');
}
}
The validate() method on the $request object returns an array (see API docs) containing the data that passed validation. If validation fails, a JSON response (which includes validation errors) is generated and returned to the client that made the request.
The code statement you're highlighting in your question is informing you that the variable $val is an array, however, you're attempting to access some data within $val using the object operator (->) as though it were an object.
If that code statement were to actually be executed, you'd see an exception message because of this (there is no errors() method on the $val array).

Laravel - voyager admin dimmer statistic

I have laravel project with voyager admin panel. Right now I need to see statistics on my admin dashboard for products in stores but only from today. So it needs to show me all products made today, to count it and show it on my dashboard.Let me show my code:
Here is my DeltaDimmer.php:
<?php
namespace TCG\Voyager\Widgets;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use TCG\Voyager\Facades\Voyager;
use Carbon\Carbon;
use App\Storeone;
class DeltaDimmer extends BaseDimmer
{
/**
* The configuration array.
*
* #var array
*/
protected $config = [];
/**
* Treat this method as a controller action.
* Return view() or other content to display.
*/
public function run()
{
$count = Storeone::where('created_at', '=', Carbon::today())->count();
//$count = \App\Storeone::where('created_at', '=', Carbon::today())->count();
$string = 'Rad: ';
return view('voyager::dimmer', array_merge($this->config, [
'icon' => 'voyager-eye',
'title' => "{$string} {$count}",
'text' => 'Optika Podgorica/Delta',
'button' => [
'text' => 'Prikazi',
'link' => route('voyager.optikadelta.index'),
],
'image' => voyager_asset('images/widget-backgrounds/04.jpeg'),
]));
}
/**
* Determine if the widget should be displayed.
*
* #return bool
*/
public function shouldBeDisplayed()
{
return Auth::user()->can('browse', Voyager::model('Post'));
}
}
So this is my DeltaDimmer.php. This line $count = Storeone::where('created_at', '=', Carbon::today())->count(); should count my products in Storeone only for today but right now it is showing me 0 and I made a few a products just for test. What I'm doing wrong?
use whereDate instead of comparing with only where
$count = Storeone::whereDate('created_at', Carbon::today())->count();

Middleware filter on all my route group except one

I have a problem for activate a middlware on a route group on laravel 5.7.
It's a simple middlware for filter post (centre in my case) which is or not to the logged user .
I activate the middleware on a group of 4 routes (edit, delete, show and destroy) and it's ok for all but not for update. For update nobody can do it.
I have this middlware in Centrepolicy
<?php
namespace App\Policies;
use Illuminate\Support\Facades\Auth;
use App\Models\Auth\User;
use App\models\Centre;
use Illuminate\Auth\Access\HandlesAuthorization;
class CentrePolicy
{
use HandlesAuthorization;
public function manage(User $user, Centre $centre)
{
if(!Auth::user()->hasRole('administrator')) {
return $user->id === $centre->user_id;
}
return true;
}
My route
/*
* All route names are prefixed with 'admin.auth'.
*/
Route::group([
'prefix' => 'auth',
'as' => 'auth.',
'namespace' => 'Auth',
'middleware' => ['permission:voir liste centre']
], function () {
Route::group(['namespace' => 'Centre'], function () {
Route::get('centres/create', 'CentreController#create')->name('centre.create');
Route::get('centres', 'CentreController#index')->name('centre.index');
Route::post('centres/store', 'CentreController#store')->name('centre.store');
});
Route::group(['prefix' => 'centres/{centre}', 'namespace' => 'Centre', 'middleware' => ['can:manage,centre']], function () {
Route::get('/edit', 'CentreController#edit')->name('centre.edit');
Route::get('/show', 'CentreController#show')->name('centre.show');
Route::put('/update', 'CentreController#update')->name('centre.update');
Route::get('/delete', 'CentreController#destroy')->name('centre.destroy');
});
my controller
<?php
namespace App\Http\Controllers\Backend\Auth\Centre;
use Illuminate\Http\Request;
use App\Models\Centre;
use App\Models\Auth\user;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class CentreController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Guard $auth)
{
/// $centres = centre::get()->paginate(5);
$centres = DB::table('centres')->paginate(10 );
if(!Auth::user()->hasRole('administrator')) {
$centres = $auth->user()->centre()->paginate(10);
}
return view('backend.centre.index', compact('centres'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$centre = new Centre;
return view('backend.centre.createcentre', ['centre' => $centre ]);
/// return view('backend.centre.createcentre');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$centres = new Centre($request->all());
$centres->user_id = Auth::user()->id;
$centres->save();
return redirect()->route('admin.auth.centre.index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show(Centre $centre)
{
return view('backend.centre.show', compact('centre'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit(Centre $centre)
{
return view('backend.centre.editcentre', compact('centre'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, Request $request)
{
$centres = Centre::find($id);
$centres->update($request->all());
return redirect()->route('admin.auth.centre.index');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy(Centre $centre)
{
$centre->delete();
return redirect()->route('admin.auth.centre.index');
}
}
And my model
<?php
namespace App\Models;
use App\Models\Auth\user;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Traits\HasRoles;
class Centre extends Model
{
protected $fillable = ['titre', 'description', 'enligne', 'user_id', 'capacite', 'slug'];
/*
public function setSlugAttribute($value)
{
if (empty($slug)) {
$this->attributes['slug'] = str_slug($this->titre);
}
}
*/
public function user()
{
return $this->belongsTo(User::class);
}
My form for edit route is
<?php
///dd($centre);
if($centre->id){
$options = ['method' =>'put', 'route' =>['admin.auth.centre.update', $centre]];
} else {
$options = ['method' =>'post', 'route' => ['admin.auth.centre.store']];
}
?>
{!! Form::model($centre, $options) !!}
<div class="form-group">
{{ Form::label('Titre', 'Titre', ['class' => 'control-label']) }}
{!! Form::text('titre', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{{ Form::label('description', 'description', ['class' => 'control-label']) }}
{!! Form::textarea('description', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{{ Form::label('capacité maximum', 'capacite', ['class' => 'control-label']) }}
{!! Form::textarea('capacite', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::hidden('enligne', '0') !!}
{!! Form::checkbox('enligne', '1' , null) !!}
</div>
{!!Form::submit("Envoyer", ['class' => 'btn btn-primary'])!!}
{!! Form::close() !!}
When i arrive on the update page on admin/auth/centres/13/update i'm on a 403 error and in the debug bar i have 3 gate, 2 first are ok and last :
success
array:4 [▼
"ability" => "view backend"
"result" => true
"user" => 1
"arguments" => "[]"
]
success
array:4 [▼
"ability" => "voir liste centre"
"result" => true
"user" => 1
"arguments" => "[]"
]
error
array:4 [▼
"ability" => "manage"
"result" => null
"user" => 1
"arguments" => "[0 => 13]"
]
I think there is a problem with argument but this route is the same than delete/show/destroy so i don't understand
edit today i try to write the middleware like that :
public function manage(User $user, Centre $centre)
{
return true;
}
But nothing to do, don't work. What action can desactive this middleware only on the update route because it's active and ok on 3 another routes?
I think the problem is you are trying to access id as a first parameter in the function and Request as second. The way it is supposed to work with Laravel is that, if you need Request inside the function, it always must be first parameter inside the function and then all the other parameters can follow, if for some reason you don't need Request and you don't include it as a function parameter then you can use other parameter as first one, but as soon as you add Request as one of parameters, it needs to be the first parameter.
So a simple fix I think would be:
...
public function update(Request $request, $id) {
...
EDIT: After you've updated your answer with showing us how u are sending the id of the model yo u are updating, it seems to me you are sending it wrong. It should be something along these lines:
...
$options = ['method' =>'put', 'route' => ['admin.auth.centre.update', $centre->id]];
...
EDIT: Another thing that came to my mind is why are you using Auth::user() from inside the Policy when you already got the Authenticated user within $user variable?
Try changing your if statement code to this:
...
if(!$user->hasRole('administrator')) {
return $user->id === $centre->user_id;
}
...

Edit file name in entity with Symfony

Hello (excuse my English, not too confident with it)
I'm actually working on a Symfony website that display some spectacles' information.
For now, I need to add an image when I create one of them. I managed to do so with the help of this tutorial.
It basically works like this: I upload an image into site's directory and then send file's name to the entity (Store in a MySQL database). I can then display the image in spectacle's details.
The issue appeared when I want to edit a spectacle. I can't update the image's name. I have two only possibilities are to 1/not edit the entity, or to 2/change the image name and then get a random one that I can't display anymore (these names are usually like /tmp/phpWb8kwV)
My image is instantiate like this in the entity (in Spectacle.php):
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255)
* #Assert\NotBlank(message="Veuillez ajouter une image à votre spectacle.")
* #Assert\File(mimeTypes={ "image/png" })
*/
private $image;
And the FormType for the spectacle's form is made like this (in SpectacleType.php):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image',FileType::class, array(
'label' => 'Image du spectacle',
'required' => false, //(Still need to provide a file to finalize the creation/edit)
));
}
And the controller to acces this page is made like this (in SpectacleController.php):
/**
* Creates a new spectacle entity.
*
* #Route("/new", name="admin_spectacle_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$spectacle = new Spectacle();
$form = $this->createForm('FabopBundle\Form\SpectacleType', $spectacle);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
$em->persist($spectacle);
$em->flush();
return $this->redirectToRoute('admin_spectacle_show', array('id' => $spectacle->getId()));
}
return $this->render('spectacle/new.html.twig', array(
'spectacle' => $spectacle,
'form' => $form->createView(),
));
}
The function that is routed to the edit view is approximatively the same, but i can't use
$spectacle->setImage($fileName);
There is two possibilities to solve this: I would like being able to update the new filename in the entity (with the other information) or being able to update the entity without changing filename.
I hope I was clear enough to explain my problem...
Thanks in advance for your responses.
I had this problem when trying to upload a PDF/TEXT.. file.
But for managing images, I advice you to use ComurImageBundle, it helps you a lot and your problem will be resolved.
It's very simple, you download the bundle like it's explained in this link.
Then you modify your code like this :
1/ Instantiation of your image in Spectacle.php (your image is stored in the DB like string)
/**
* #ORM\Column(type="string", nullable=true)
*/
private $image;
2/ Update your base ( php bin/console doctrine:schema:update --force)
3/ Add these functions to your Spectacle.php after updating your DB schema, these functions let you upload and stock your images under specific directory (web/uploads/spectacles) and don't forget to add this two libraries
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #Assert\File()
*/
private $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* #ORM\PrePersist
*/
public function preUpload()
{
if (null !== $this->file) {
$this->image = uniqid() . '.' . $this->file->guessExtension();
}
}
/**
* #ORM\PostPersist
*/
public function upload()
{
if (null === $this->file) {
return;
}
// If there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->file->move($this->getUploadRootDir(), $this->image);
}
public function getUploadDir()
{
return 'uploads/spectacles';
}
public function getBaseUrl()
{
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
return substr($pathInfo['dirname']."/", 1);
}
public function getUploadRootDir()
{
return $this->getBaseUrl() . $this->getUploadDir();
}
public function getWebPath()
{
return null === $this->image ? null : $this->getUploadDir() . '/' . $this->image;
}
public function getAbsolutePath()
{
return null === $this->image ? null : $this->getUploadRootDir() . '/' . $this->image;
}
4/ Modify the FormType (SpectacleType.php)like this
use Comur\ImageBundle\Form\Type\CroppableImageType;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom')
->add('lieu')
->add('dateSpectacle', null, array(
'label' => 'Date du spectacle',
))
->add('annee')
->add('image', CroppableImageType::class, array('label' => 'Image', 'required' => true,
'uploadConfig' => array(
'uploadUrl' => $myEntity->getUploadDir(), // required - see explanation below (you can also put just a dir path)
'webDir' => $myEntity->getUploadRootDir(), // required - see explanation below (you can also put just a dir path)
'fileExt' => '*.png', // required - see explanation below (you can also put just a dir path)
'showLibrary' => false,
),
'cropConfig' => array(
'minWidth' => 128,
'minHeight' => 128,
'aspectRatio' => true,
)
));
}
5/ Remove all these lines from your controller you won't need them
//--------------------------------------------------------------------
$file = $spectacle->getImage();
$fileName = (md5(uniqid())).'.'.$file->guessExtension();
// moves the file to the directory where image are stored
$file->move(
$this->getParameter('img_directory'), //(Define in the service.yml)
$fileName
);
$spectacle->setImage($fileName); //(Don't know how to handle file names without this line)
//---------------------------------------------------------------------
6/ That's it you can call the form of your image in new.html.twig and edit.html.twig, all will get well, try it please and notify me if there is any problem.
The solution was stupid ...
In fact, the controller to access the edit route didn't have those lines:
$em = $this->getDoctrine()->getManager();
...
$em->persist($spectacle);
$em->flush();
I need to finish this quickly. If i have more time later, i'll try to make it work with the ComurImageBundle.
Thank you for your help, i'll be more carefull next time ...

yii2 load model in controller doesnt load Form's posted data

This is my view file and it has one form that should post a file with a text variable data of 0000000005. But for some reason the load function inside the controller does not populate these data.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model backend\models\customs\UploadForm */
/* #var $form ActiveForm */
?>
<div class="vendor_file_upload_form">
<?php $form = ActiveForm::begin(
['id' => 'form-files'],
['options' => ['enctype' => 'multipart/form-data']]
); ?>
<?= $form->field($model, 'AppFile')->fileInput() ?>
<?= $form->field($model,'apid')->textInput(); ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Submit'), ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div><!-- vendor_file_upload_form -->
This is my controller
public function actionFiles($id=null)
{
$model = new UploadForm();
if ($model->load(Yii::$app->request->post()))
{
$model->AppFile = UploadedFile::getInstance($model, 'AppFile');
if ($model->upload())
{
\Yii::$app->getSession()->setFlash('success', 'File has been successfully uploaded.');
return $this->redirect(['index']);
}
else
{
\Yii::$app->getSession()->setFlash('error', 'Wrong File Format , Try proper format.');
return $this->redirect(['index']);
}
}
}
I found that for some reason Load data does not load all the posted form parameters. I have spent 3 hours and I am still unable to understand why my form data is not being transferred properly.
I checked the Payload and I found following which means my data is coming fine but load function is not loading properly.
------WebKitFormBoundaryZfszVA0IZuj02ZFT Content-Disposition: form-data; name="_csrf-backend"
UEZaLmZ4MzEWExBjLz8LSWAnHG9SGgFhaBcqbycRZWc1dGtCAD9JYg==
------WebKitFormBoundaryZfszVA0IZuj02ZFT Content-Disposition: form-data; name="UploadForm[AppFile]"
------WebKitFormBoundaryZfszVA0IZuj02ZFT Content-Disposition: form-data; name="UploadForm[AppFile]"; filename="falcon-wallpaper.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryZfszVA0IZuj02ZFT Content-Disposition: form-data; name="UploadForm[apid]"
0000000005
------WebKitFormBoundaryZfszVA0IZuj02ZFT--
EDIT:
Below is my model file,
<?php
/**
* Created by PhpStorm.
* Date: 1/8/2017
* Time: 9:52 PM
*/
namespace backend\models\customs;
use backend\models\ApplicationFiles;
use yii\base\Model;
use yii\web\UploadedFile;
/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $AppFile; //files which needs to be uploaded
public $apid; //application_id
/**
* #return array the validation rules.
*/
public function rules()
{
return [
[['apid'], 'required','message'=>'No Application Id found'],
[['AppFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
//upload on the backed/uploads folder with time stamp as the file name
if ($this->validate()) {
$File_name = time() . '.' . $this->AppFile->extension;
if($this->AppFile->saveAs(\Yii::$app->basePath.'/uploads/' .$File_name ))
{
$model = new ApplicationFiles();
$model->name = $File_name;
$model->path = \Yii::$app->basePath.'/uploads/' .$File_name;
$model->application_id = $this->apid;
// $model->type =
$model->save();
}
return true;
}
else
{
return false;
}
}
}
?>

Categories