how to update uploaded file yii2 - yii2

controller-
public function actionUpdate($id) {
$model = $this->findModel($id);
$model->scenario = 'update';
if ($this->request->isPost) {
if ($model->load($this->request->post())) {
$model->image = UploadedFile::getInstance($model, 'image');
$fileName = time().'.'. $model->image->extension;
$model->image->saveAs('uploads/'. $fileName);
$model->image = $fileName;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
}

Try This
use yii\web\UploadedFile;
public function actionUpdate($id) {
$model = $this->findModel($id);
if ($this->request->isPost) {
if ($model->load($this->request->post())) {
$model->image = UploadedFile::getInstance($model,'image');
if ( $model->image ){
//rename the image
$model->image->saveAs('upload/' .$model->id. '.' . $model->image->extension);
//save the name image to database
$model->image = 'upload/' .$model->id. '.' . $model->image->extension;
}
}
}
}
if you want to keep the old file
add specification , example date now
$model->image->saveAs('upload/' .$model->id.'.'.date("Y-m-d").'.' $model->image->extension);

Related

The file "C:\xampp\tmp\php8911.tmp" does not exist

I after install
composer require intervention/image
I want to upload image and after submit a form, I get this error.
The file "C:\xampp\tmp\php1D5F.tmp" does not exist
public function store(ArticleRequest $request)
{
auth()->loginUsingId(1);
$imagesUrl = $this->uploadImages($request->file('images'));
$article = auth()->user()->article()->create(array_merge($request->all(), ['images' => $imagesUrl]));
$article->categories()->attach(request('category'));
return redirect(route('articles.index'));
}
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath) , $filename);
$sizes = ["300" , "600" , "900"];
$url['images'] = $this->resize($file->getRealPath() , $sizes , $imagePath , $filename);
$url['thumb'] = $url['images'][$sizes[0]];
return $url;
}
private function resize($path , $sizes , $imagePath , $filename)
{
$images['original'] = $imagePath . $filename;
foreach ($sizes as $size) {
$images[$size] = $imagePath . "{$size}_" . $filename;
Image::make($path)->resize($size, null, function ($constraint) {
$constraint->aspectRatio();
})->save(public_path($images[$size]));
}
return $images;
}
I tried Change the code:
$imagesUrl = $this->uploadImages($request->file('images'));
return $imagesUrl;
It displaied return $imagesUrl well.
images
300 "/upload/images/2018/300_tvto.jpg"
600 "/upload/images/2018/600_tvto.jpg"
900 "/upload/images/2018/900_tvto.jpg"
original "/upload/images/2018/tvto.jpg"
thumb "/upload/images/2018/300_tvto.jpg"
I think problem from array_merge
So what's the solution?
You need to convert ArticleRequest to Request and bring it to the controller page like below.
public function store(Request $request)
{
$this->validate(request(),[
'title' => 'required|max:250',
'type' => 'required',
'description' => 'required',
'image' => 'required|mimes:jpeg,png,bmp',
'path.*' => 'required|mimes:avi,mp4,.mov,wmv',
'price' => 'required',
]);

array saving cakephp 3 savemany

Hi can someone know this i am beginner in Cakephp i tried to upload multiple images but it wont save.
Controller:
public function add() {
if ($this->request->is('post')) {
//$data = $this->request->getData();
if(!empty($_FILES['photo']['name'])){
$count = count($_FILES['photo']['name']);
for ($i=0; $i < $count; $i++) {
$filename = $_FILES['photo']['name'][$i];
$type = $_FILES['photo']['type'][$i];
$tmp = $_FILES['photo']['tmp_name'][$i];
$error = $_FILES['photo']['error'][$i];
$size = $_FILES['photo']['size'][$i];
$uploadPath = '../uploads/files/';
$file[$i]['user_id'] = $this->Auth->user('id');
$file[$i]['filename'] = $filename;
$file[$i]['file_location'] = $uploadPath;
$file[$i]['file_type'] = $type;
$file[$i]['file_size'] = $size;
$file[$i]['file_status'] = 'Active';
$file[$i]['created'] = date("Y-m-d H:i:s");
$file[$i]['modified'] = date("Y-m-d H:i:s");
}
$table = TableRegistry::get('files');
$entities = $table->newEntities($file);
if($table->saveMany($entities)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}
but when i tried to debug all good but in saving it wont work! does my code has problem, can someone help me how to fix my add function
View:
echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']);
You are trying to save one record once using saveMany().
public function add()
{
if ($this->request->is('post')) {
$table = TableRegistry::get('files');
$uploadPath = '../uploads/files/';
if(!empty($_FILES['photo'])){
foreach ($_FILES['photo'] as $EachPhoto) {
$data[] = [
'user_id' => $this->Auth->user('id'),
'filename' => $EachPhoto['name'],
'file_location' => $uploadPath,
'file_type' => $EachPhoto['type'],
'file_size' => $EachPhoto['size'],
'file_status' => 'Active',
'created' => date("Y-m-d H:i:s")
];
}
$entities = $table->newEntities($data);
if($this->Files->saveMany($entitie)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('Unable to upload file, please try again.'));
}
} else {
$this->Flash->error(__('Please choose a file to upload.'));
}
}
}

Send mail on actionCreate

I have a system that works by the intranet and I would like to know how best to send an alert email in actionCreate?
I did as below, the email is sent correctly, but if the internet is offline an unfriendly error message appears.
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
} else {
// error in saving model
}
}
return $this->render('create', [
'model' => $model,
]);
}
Try this (don't save model if email not sended)
public function actionCreate()
{
$model = new Todolist();
if ($model->load(Yii::$app->request->post())) {
$file = $model->uploadImage();
$transaction = $model->getDb()->beginTransaction();
try{
if ($model->save()) {
if ($file !== false) {
$idfolder = Yii::$app->user->identity->id;
if(!is_dir(\Yii::$app->getModule('task')->params['taskAttachment'])){
mkdir(\Yii::$app->getModule('task')->params['taskAttachment'], 0777, true);
}
$path = $model->getImageFile();
$file->saveAs($path);
}
Yii::$app->session->setFlash("task-success", "Atividade incluída com sucesso!");
\Yii::$app->mailer->compose('#app/mail/task')
->setFrom('intranet#sicoobcrediriodoce.com.br')
->setTo($model->responsible->email)
->setSubject(Yii::$app->params['appname'].' - '.\Yii::$app->getModule('task')->params['taskModuleName']. ' - Nova Tarefa : #'. $model->id)
->send();
return $this->redirect(['index']);
}
}
catch(Exception $e)
{
$transaction->rollBack();
throwe $e;
//unlik savedFile if exist
}
}
return $this->render('create', [
'model' => $model,
]);
}
or use mail queue to save mail in databases and send via cron

Auto create folder and upload image in Yii2

I have created ..\frontend\web\uploads.
This is the function Create in PropertiesControllers.php configuration that I have:
public function actionCreate()
{
$model = new Properties();
$date = date('YmdHis');
if ($model->load(Yii::$app->request->post())) {
$file = \yii\web\UploadedFile::getInstance($model, 'url_img');
if (!empty($file))
$model->url_img = $date.$file;
if($model->save())
{
if (!empty($file))
$file->saveAs( Yii::getAlias('#frontend') .'/web/uploads/'.$date.$file);
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', ['model' => $model]);
} else {
return $this->render('create', ['model' => $model]);
}
}
It works when uploads is existed. But I want to redirect to new folder in uploads as uploads\img
if (!empty($file))
$file->saveAs( Yii::getAlias('#frontend') .'/web/uploads/img'.$date.$file);
It show error because ../web/uploads/img is not existed.
I don't know to solve this issue. Help me!
I suggest you to create the img folder before $file->saveAs(. In Yii2,you can make use of yii\helpers\FileHelper to create a directory. If your problem is like img folder does not exists inside uploads,then you can create the folder with yii\helpers\FileHelper as
$path = Yii::getAlias('#frontend')."/web/uploads/img";
\yii\helpers\FileHelper::createDirectory($path, $mode = 0775, $recursive = true);
Full code
public function actionCreate() {
$model = new Properties();
$date = date('YmdHis');
if ($model->load(Yii::$app->request->post())) {
$file = \yii\web\UploadedFile::getInstance($model, 'url_img');
if (!empty($file))
$model->url_img = $date . $file;
if ($model->save()) {
if (!empty($file)) {
$path = Yii::getAlias('#frontend') . "/web/uploads/img";
//here you create the folder
if (\yii\helpers\FileHelper::createDirectory($path, $mode = 0775, $recursive = true)) {
$file->saveAs(Yii::getAlias('#frontend') . '/web/uploads/img/' . $date . $file);
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', ['model' => $model]);
} else {
return $this->render('create', ['model' => $model]);
}
}
More info about FileHelper here http://www.yiiframework.com/doc-2.0/yii-helpers-filehelper.html

Kohana 3.2 select issue

I have table with 'servers' name in my db. So when I want to add there some data with that code it's just ok:
public function action_add()
{
$serverGameId = (int)Arr::get($_POST, 'serverGameId', '');
$newServerName = Arr::get($_POST, 'newServerName', '');
try
{
$server = new Model_Server();
$server->Name = $newServerName;
$server->GameId = $serverGameId;
$server->save();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "serverId" => $server->Id));
return true;
}
Here is a model:
class Model_Server extends ORM {
protected $_table_name = 'servers';
public function rules()
{
return array(
'Name' => array(
array('not_empty'),
)
);
}
}
But I have problem when I try to select it from the table:
public function action_servers()
{
$gameId = (int)Arr::get($_POST, 'gameId', '');
if($gameId == -1) return false;
try
{
$servers = ORM::factory('server')
->where('GameId', '=', $gameId)
->find_all();
}
catch(ORM_Validation_Exception $e)
{
echo json_encode(array("success" => false, "errors" => $e->errors('validation')));
return false;
}
$this->request->headers['Content-Type'] = 'application/json';
echo json_encode(array("success" => true, "servers" => $servers, "gameId" => $gameId));
return true;
}
I already try to solve problem with change code inside of try block on:
$servers = DB::select('servers')->where('GameId', '=', $gameId);
Even when I try just get all my servers from db without '->where' it's doesn't work.
Any ideas?
Try print_r($servers); inside try block to see what you get from model.
And $servers is some class with results - use foreach to get result (one by one)
$results = array();
foreach($servers as $row) {
//echo $row->Name;
$results[] = $row->Name;
}
Or
$results = array();
foreach($servers as $row) {
//echo $row->as_array();
$results[] = $row->as_array();
}