View file after uploading - php

How can I redirect the user to a view page after uploading file?
Now it works only when I write id of db entry in view
I'm totally new to php and yii 2.
Controller
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file && $model->validate()) {
$postFile = Yii::$app->request->post();
$directory = Yii::getAlias('#frontend/web/uploads');
$uid = Yii::$app->security->generateRandomString(6);
$fileName = $uid . '.' . $model->file->extension;
$filePath = $directory . '/' . $fileName;
$path = 'http://frontend.dev/uploads/' . $fileName;
$userinfo = new webminfo();
$userinfo->uid = $uid;
$userinfo->author_id = Yii::$app->user->id;
$userinfo->path = $filePath;
$userinfo->url = $path;
$userinfo->created_at = time();
$userinfo->ip = Yii::$app->getRequest()->getUserIP();
$userinfo->save();
if ($model->file->saveAs($filePath)) {
Yii::$app->session->setFlash('success', 'Success');
return $this->redirect(['view', 'id' => $userinfo->uid]);
}
}
else {
Yii::$app->session->setFlash('error', 'Error');
}
}
return $this->render('upload', ['model' => $model]);
}
public function actionView($id) {
$model = new webminfo();
return $this->render('view', [
'id' => $id,
'model' => $model,
]);
}
View
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\Url;
use app\models\webminfo;
$this->title = 'View';
$this->params['breadcrumbs'][] = $this->title;
?>

Use $uid instead of $userinfo->uid as follows in your redirect function
return $this->redirect(['view', 'id' => $uid]);

Related

Laravel : Update field when value is exist

I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}

Unable to open file for reading [attachments/.jpg] using yii2

This program is an Email with attachment , but when I try to click submit button it say.
Swift_IoException
Unable to open file for reading [attachments/.jpg]
Here is my EmailController.php Code
public function actionCreate()
{
$model = new emails();
if ($model->load(Yii::$app->request->post()))
{
$model->attachment=UploadedFile::getInstance($model,'attachment');
if($model->attachment)
{
$time=time();
$model->attachment->saveAs('attachments/'.$time.'.'.$model->attachment->extension);
$model->attachment='attachments/'.'.'.$model->attachment->extension;
}
if($model->attachment)
{
$value=Yii::$app->mailer->compose()
->setFrom([ 'rodulfoalmeda#gmail.com'=>'Sample' ])//->setFrom([ $company->company_email=>$company->company_name ])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->attach($model->attachment)
->send();
}else
{
$value=Yii::$app->mailer->compose()
->setFrom([ 'rodulfoalmeda#gmail.com'=>'Sample' ])//->setFrom([ $company->company_email=>$company->company_name ])
->setTo($model->receiver_email)
->setSubject($model->subject)
->setHtmlBody($model->content)
->send();
}
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
You are ommiting $time in assigning to $model->attachment property.
$time = time();
$path = 'attachments/' . $time . '.' . $model->attachment->extension;
$model->attachment->saveAs($path);
$model->attachment = $path;

Yii2: failed to open stream: No such file or directory

i have problem with my upload/update function in Yii2 framework.
My update function:
public function actionUpdate($id) {
$model = $this->findModel($id);
// $model->scenario = 'update';
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$uploadDir = Yii::getAlias('#web/web/uploads') . Yii::getAlias('#web/web/uploads');
$uploadPath = Yii::getAlias('#web/web/uploads');
$model->save();
$imageProject = $model->id;
//Main Image
$image = UploadedFile::getInstance($model, 'main_image');
if ($image) {
$imgProject = 'project_' . $imageProject . '.' . $image->getExtension();
$image->saveAs($uploadDir . '/' . $imgProject);
$model->main_image = $uploadPath . '/' . $imgProject;
}
if ($model->upload()) {
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
And my params.php file :
return [
'aliases' => [
'#projectImgPath' => '#webroot/web/uploads',
'#projectImgUrl' => '#web/web/'
]
];
When i upload file in my form i have this error:
move_uploaded_file(/web/uploads/web/uploads/gallery_1_3.png): failed to open stream: No such file or directory
Anyone can help me... thank`s !
$uploadDir = Yii::getAlias('#web/web/uploads') . Yii::getAlias('#web/web/uploads');
replace with
$uploadDir = Yii::getAlias('#web/web/uploads');

Yii2: How to execute sql query after model->save()

public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post())) {
$imageName = $model->first_name;
$mobile = $model->primary_mobile;
$type = $model->room_type;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension);
//save the path in the db column
$model->id_image = 'uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I need to execute query \Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute(); after the model->save();
same query working in actionupdate() but not in actioncreate(),
Is it possible with behaviours?
You could override afterSave method of ActiveRecord or create a trigger directly on db
Documentation: http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#afterSave%28%29-detail
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
// your code here
Yii::$app->db->createCommand(sprintf("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '%s'", $this->room_type))->execute();
}

update a record without removing the uploaded file in yii

I need to UPDATE record with out changing or deleting filename(i mean file) , OR reinsert file again so how i can do this?
here is my actionCreate, How i can write update?
public function actionCreate() {
$model = new Page;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = CUploadedFile::getInstance($model, 'filename');
if ($model->save()) {
if ($model->filename !== null) {
$dest = Yii::getPathOfAlias('application.uploads');
$model->filename->saveAs($dest . '/' . $model->filename->name);
$model->save();
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
So Please can anyone find a solution
If you don't need to change or delete filename in edit/update then ignore filename (and upload part) assuming the file is alrready uploaded and you don't wish to change/delete it.
public function actionUpdate($id) {
$model = $this->loadModel($id);
$file = $model->filename;
if (isset($_POST['Page'])) {
$model->attributes = $_POST['Page'];
$model->filename = $file;
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
Try this, it's working for me -
create a upload folder outside protected directory and also give read/write permission.
actionCreate function -
public function actionCreate() {
$model = new Page();
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if(!empty( $fileName)){
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias('application') . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
if(!$model->hasErrors() && $model->validate() && $model->save(false)) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'success'));
}
}
}
actionUpdate function -
public function actionUpdate() {
$model = Page::model()->findbyPK($id);
$model->scenario = 'update';
if(isset($_POST['Page']) && !empty($_POST['Page'])){
$model->attributes = $_POST['Page'];
if(empty($_POST['Page']['filename'])) { $file_name = $model->filename; } //store existing file name into a variable if your uploading a file on update
$rand = rand(1, 999);
$myfile = CUploadedFile::getInstance($model, 'filename');
$fileName = "{$rand}-{$myfile}"; //Generate unique file name
if($model->validate()) {
if(!empty($fileName)) {
$model->filename = $fileName;
$target_dir = realpath( Yii::getPathOfAlias( 'application' ) . '/../upload');
$target_file = $target_dir . '/' . $fileName;
if(!$myfile->saveAs($target_file)){
$model->addError('filename', 'File saving error');
}
}
else {
$model->filename = $file_name; //allow existing file name
}
if( !$model->hasErrors() && $model->save(false) ) {
$this->redirect(array('view', 'id'=>$model->id, 'msg'=>'update'));
}
}
}
In model rules array define this -
array('filename', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')

Categories