URL with no corresponding view - php

I'm trying to get a fileupload working in the same way the existing one does, so I tried to look at how that one works. The original upload functionality just calls a URL (site.com/model/upload/model_id) and then the file that was selected gets saved on the server. Other than that, it renders exactly the same as the model view would (site.com/model/model_id)
Seeing that, I started looking through all server files. There is not a single file called upload, not any other mention of that URL, not even anything in the site controller. The only thing I found was in the modelController:
public function actionUpload($id) {
$model = new Model();
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file) {
$path = 'uploads/documents/'. $id .'/';
FileHelper::createDirectory($path);
$model->file->saveAs($path . $model->file->baseName . '.' . $model->file->extension);
}
return $this->render('view', ['model' => $this->findModel($id)]);
}
How does this work? I tried to replicate it with a copy of this function with a different name, but that then just gives me a page not found error.
The code for the documentupload in the view is this:
<?php $form = ActiveForm::begin(['action' => \yii\helpers\Url::to(['upload', 'id' => $model->id]), 'options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'file')->fileInput(['style' => ''])->label(false) ?>
<?= Html::submitButton('Upload', ['class' => 'btn-success']) ?>
<?php ActiveForm::end() ?>
Edit: Solved by adding a boolean parameter to the actionUpload function.

Related

Laravel get path of saved file from upload

I have a laravel upload for file (along with other data that is passed to the database) Everything works. But I just can't figure out how to save the path of the file that is saved.
Here is my controller function:
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'logo' => 'nullable',
'original_filename' => 'nullable',
]);
//This is where the file uploads?
if ($request->hasFile('logo')) {
$request->file('logo')->store('carrier_logo');
$request->merge([
'logo' => '',//TODO: get file location
'original_filename' => $request->file('logo')->getClientOriginalName(),
]);
}
Carrier::create($request->all());
return redirect()->route('carriers.index')->with('toast', 'Carrier created successfully.');
}
The thing I want to achieve:
I want logo to fill with something like carrier_logo/ZbCG0lnDkUiN690KEFpLrNcn2exPTB8mUdFDwAKN.png
The thing that happened every time I tried to fix it was that it placed the temp path in the database. Which ended up being something in the PHP install directory.
Just assign result to variable:
$path = $request->file('logo')->store('carrier_logo');
According to docs
Then you can do with $path variable whatever you want.
just assign the value like this.
$location=base_path('img/'.$filename);
and save it in db.
You could do this:
For FileName
$fileName = $request->file('test')->getClientOriginalName();
OR
$fileName = $request->user()->id.'.'.$request->file('logo')->getClientOriginalExtension();
$imageDirectory = 'logo_images';
$path = $request->file('logo')->storeAs($imageDirectory, $fileName);
dd($path);

Yii2 Page link to another with the use of button

This is my first time using Yii2 so i am confused on how it works. I have this card page in my views/people/card.php .However i can only access the page through web/people/card. Why?
I am able to link the button in card.php to _card.php (without changing the url) using controller but how do i link my button in _card.php to _data.php?
My controller
public function actionCard()
{
$dataProvider = new ActiveDataProvider([
'query' => People::find(),
]);
$model = '';
if (Yii::$app->request->post() && isset($_POST['card'])) {
if(isset($_POST['selection'])){
$model = People::find()->select('id, name, ic')->where(['id' => $_POST['selection']])->all();
$content = $this->renderPartial('_card',['model'=>$model]);
$selection = implode(',', $_POST['selection']);
}
return $this->render('_design', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
First You can only access the page through web/people/card. because this is the route managed by yii (is one of the possibile routing way you can see more in this guide
Second how do you link button in _card.php to _data.php? (in another controller)
also for this you can do using the routing rules above. In this case you should add the controller name to the route(controller/view) eg:
$content = $this->renderPartial('data/_data',['model'=>$model]);
but remember is not a good practice to use view from different controller.

Lines of code duplicated in Controller, where to create a method with them?

Aloha, I have two methods in my Controller, one for setting the profile picture and the other for updating it. I'm using this lines of code in both methods:
$user = Auth::user();
if (Input::file('image')) {
$image = Image::make(Input::file('image'));
$fullName = Input::file('image')->getClientOriginalName();
$extension = Input::file('image')->getClientOriginalExtension();
$pathToCreate = public_path() .'/images/'. $user->email . '/';
$fullPath = $pathToCreate . $user->email . '.' . $extension;
$pathDatabase = 'images/' . $user->email . '/' . $user->email . '.' .$extension;
// Creating directory if it does not exists
File::exists($pathToCreate) or File::makeDirectory($pathToCreate);
$image->resize(null, 145, function ($constraint) { $constraint->aspectRatio(); })
->crop(130,130)
->save($fullPath);
$user->picture = $pathDatabase;
I want to create a method with this lines of code but I feel that the controller is not a good place for it. Where should I place this method?
Generally speaking, it depends on the purpose of the code. If this is the only place on your site that you'll be using that code, it is perfectly acceptable to include the code a private method in the Controller class.
If this code will be used in other controllers, you probably want to create a service class to handle this. This would equate to something like the following when used in your controller:
$user->picture = $this->fileUploadService->process( Input::file('image') );
The extremely short answer is: put it where it makes the most sense. A generic solution should be broadly available as a service. A specific solution should go where ever that specificity is needed (controller, repository, model, etc.).
You should check out Laravel-Stapler. Very useful for handling image uploads in Laravel. https://github.com/CodeSleeve/laravel-stapler
Rather then saving an image and checking if it exists you can attach (or "Staple") an image to a model.
An example taken from the docs on how to setup the form is below.
<?= Form::open(['url' => action('UsersController#store'), 'method' => 'POST', 'files' => true]) ?>
<?= Form::input('first_name') ?>
<?= Form::input('last_name') ?>
<?= Form::file('picture') ?>
<?= Form::submit('save') ?>
<?= Form::close() ?>
The model would have something like this in the controller:
$this->hasAttachedFile('picture', [
'styles' => [
'thumbnail' => '100x100',
'large' => '300x300',
'pictureCropped' => '75x75#'
],
'url' => '/system/:attachment/:id_partition/:style/:filename',
'default_url' => '/:attachment/:style/missing.jpg'
]);
Then all you do in the controller is User::create(Input::all());
Checking existence of "attachments" is as easy as if ($user->picture) ...
So the saving of the file is already taking care of by Stapler and the cropping is done automatically via the 'pictureCropped' => '75x75#' configuration. This should remove enough of the code that you don't need to make another method.
Hope this helps!

Yii: How to make Dropzone Extension work?

I'm trying to add Dropzone Extension to my application in Yii, which allows asynchronous file uploading. http://www.yiiframework.com/extension/yii-dropzone/
The first thing i did was putting the downloaded folder called "dropzone" into my extensions folder "C:\xampp\htdocs\site\protected\extensions".
And here is my code for the action in the controller (MainController.php)
public function actionUpload()
{
$test = rand(100000, 999999); //TEST
var_dump($test);
$model = new UploadFile;
if(isset($_FILES['images'])){
$model->images = CUploadedFile::getInstancesByName('images');
$path = Yii::getPathOfAlias('webroot').'/uploads/';
//Save the images
foreach($model->images as $image)
{
$image->saveAs($path);
}
}
$this->render('upload', array('model' => $model));
}
the view (upload.php)
<?php
$this->widget('ext.dropzone.EDropzone', array(
'model' => $model,
'attribute' => 'images',
'url' => $this->createUrl('file/upload'),
'mimeTypes' => array('image/jpeg', 'image/png'),
'options' => array(),
));
?>
and the model (UploadFile.php)
<?php
class UploadFile extends CFormModel
{
public $images;
public function rules(){
return array
(
array(
"images",
'file',
'types' => 'jpg,gif,png',
),
);
}
}
When I run it I can see the Dropzone interface and I can add images dragging them or selection them from the file explorer.
It appears their respective progress bar and a success mark, but nothing appear in the directory of uploads, and any error is shown neither in the IDE (Netbeans) nor in the Chrome console.
I did some print tests and I realize that the code inside the 'actionUpload' is being executed only the first time (when it draws the view), but when its called from the dropzone widget it do nothing.
I'd really appreciate if you have a solution for this. I'd love if someone could give me a simple working example of this extension. Thanks.
As I understand, dropzone uploads files one by one, not all together. So $model->images holds only one image object. And foreach cycle fails.

Miles Johnson's file uploader generates empty files

I'm using CakePHP 2.3.6 and just added Miles Johnson's image uploader.
Everything seems to work when I use my View to upload a photo I get a success return.
A file gets created with the right name, so formatName function seams to work.
But the size of the created file is always only 56bytes. No matter how big the originally uploaded file was.
I have the strong feeling that there is something wrong with user rights or with configuration of apache server that it maybe does't alow upload.
Does anybody know what could let me create a file but not put content into this file?
On the Uploader Howto there is nothing said about any changes I would have to do on apache or php configuration.
View:
<?php
echo $this->Form->create('Site');
echo $this->Form->input('startpageImage', array('type' => 'file'));
echo $this->Form->end('Submit');
?>
Model:
public $actsAs = array(
'Uploader.Attachment' => array(
'startpageImage' => array(
'tempDir' => TMP,
'finalPath' => '/img/uploads/',
'nameCallback' => 'formatName',
)
)
);
public function formatName($name, $file) {
return sprintf('%s-%s', $this->field('id'), $name);
}
I wrote a email to Miles Jones and he found the mistake immediately:
View:
<?php
echo $this->Form->create('Site', array('type' => 'file'));
echo $this->Form->input('startpageImage', array('type' => 'file'));
echo $this->Form->end('Submit');
?>
I forgot the
, array('type' => 'file')
in the first line of Form.
No black magic, no rocket science... :)

Categories