How can I create a thumb image from uploaded image?
I tried this in my controller:
<?php
namespace backend\controllers;
use Yii;
use app\models\Employee;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\imagine\Image;
public function actionCreate() {
$model = new Employee();
$model->added_date_time = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model,'avatar');
if (!empty($model->file)) {
$imageName = Yii::$app->security->generateRandomString();
$model->file->saveAs('uploads/' . $imageName . '.' . $model->file->extension);
$model->avatar = $imageName . '.' . $model->file->extension;
$file = 'uploads/' . $imageName . '.' . $model->file->extension;
Image::thumbnail($file, 200, 200)->save('uploads/thumb/', ['quality' => 80]);
}
if ($model->save()) {
$this->redirect(\Yii::$app->urlManager->createUrl('employee'));
}
} else {
return $this->render('create', ['model' => $model]);
}
}
And it doesn't work. Image is uploaded, but the thumb isn't created.
Can anyone help?
Set proper paths to the original and thumbnail images, then save the result:
$imgPath = Yii::$app->basePath . '/uploads/'; // as an example
$imgName = Yii::$app->security->generateRandomString();
$fileExt = '.' . $model->file->extension;
$originFile = $imgPath . $imgName . $fileExt;
$thumbnFile = $imgPath . $imgName . '-thumb' . $fileExt;
// Generate a thumbnail image
Image::thumbnail($originFile, 200, 200)->save($thumbnFile, ['quality' => 80]);
Please try with this code
$file = Yii::$app->basePath.'/uploads/'.$imageName.'.'.$model->file->extension;
$thumbFile = Yii::$app->basePath.'/uploads/thumb/'.$imageName.'.'.$model->file->extension;
Image::thumbnail($file, 200, 200)->save($thumbFile, ['quality' => 80]);
Related
My Qr code is not working. I have already included my libraries consisting of CIqrcode and the qrcode. Is there anything that i missed? Any guides will be appreciated. Thank you
Controller:
class Testingpage extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Testingpagemodels');
$this->load->library('Ciqrcode');
}
function QRcode($try){
QRcode::png(
$try,
$outfile = false,
$level = QR_ECLEVEL_H,
$size= 5,
$margin =2,
);
}
public function fetchqr()
{
$list = $this->Testingpagemodels->get_datatables_testing();
$json = array();
$no = $_POST['start'];
foreach ($list as $rows) {
$no++;
$first=$rows->ID_NUMBER;
$json[]=array(
'<tr><th><center><img src="testingpage/QRcode/'.$first.'" width="110px"><br>'.$rows->NAME.'<br>'.$rows->DEPARTMENT.'</center></th>', //I'm calling the function of my QR here.
);
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Testingpagemodels->count_all_testing(),
"recordsFiltered" => $this->Testingpagemodels->count_filtered_testing(),
"data" => $json,
);
//output to json format
echo json_encode($output);
}
My Dear friend you did not mention your environment is local or live in case of the production server that might be the extension issue.to avoid that use the below mention code to display your image.
<?php
// $path is path where your image is stored.
$path = "assets/custom/img/img.jpg";
$type = pathinfo($path, PATHINFO_EXTENSION);
$file_data = file_get_contents($path);
$base64_img = 'data:image/' . $type . ';base64,' .
base64_encode($file_data);
?>
Solved.
From my "Config" i have deleted this:
From
$autoload['helper'] = array('url','html','email');
To
$autoload['helper'] = array('url','html');
Now it is working. Anyone who can help me why it is an error when I include it in autoload? Is there a conflict between qrcode and email? Thank you.
This question already has answers here:
Yii Framework 2.0 Uploading Files Error finfo_file(): failed to open stream: No such file or directory
(10 answers)
Closed 3 years ago.
I'm coding a view to upload a file, the user may choose between upload it to the filesystem or upload it to the filesystem and record the filename on a datatable.
At this moment, the first stage (upload it to the filesystem only) is working, regards to the second option, the file is uploaded to the directory but I can't add the filename info to the table; I am confuse with these 2 facts: 1) I am getting this error: finfo_file(/tmp/phpKB2h1A): failed to open stream: No such file or directory, 2) the var (tplfilename) is blank
This is the View:
<?php
use yii\widgets\ActiveForm;
?>
<?php if (Yii::$app->session->hasFlash('sminfo2')): ?>
<div class="alert alert-success">
<?= Yii::$app->session->getFlash('sminfo2');?>
</div>
<?php else: ?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'tplfilename')->fileInput()->label('Choose your Template',['class'=>'label-class']) ?>
<?= $form->field($model, 'destination')->radioList(array('1'=>'Filesystem','2'=>'Datatable'))->label('File store destination:') ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
<?php endif; ?>
This is the controller's function:
public function actionUploadtpl(){
$model = new UploadtplForm();
if (Yii::$app->request->isPost) {
$model->destination = $_POST['UploadtplForm']['destination'];
$model->tplfilename = UploadedFile::getInstance($model, 'tplfilename');
if($model->destination == "1"){
if ($model->upload()) {
// file is uploaded successfully
Yii::$app->session->setFlash("sminfo2", "Template file uploaded successfully to Filesystem");
return $this->refresh();
//return;
}//end of if model upload
}//end of if model destination ==1
else{
if($model->upload()){
$model->save();
Yii::$app->session->setFlash("sminfo2", "Template file uploaded successfully to Datatable");
return $this->refresh();
}
}
}//end of isPost
return $this->render('uploadtpl', ['model' => $model]);
}//end of uploadtplform
And this is the model:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\db\ActiveRecord;
/**
* #property int $id
* #property string $tplfilename
**/
//class UploadtplForm extends Model
class UploadtplForm extends \yii\db\ActiveRecord
{
/**
* #var UploadedFile
*/
public $tplfilename; //upload filename
public $destination; //set by user on view: upload the file to filesystem or datatable
public static function tableName(){
return 'templates';
}
public function rules()
{
return [
[['tplfilename'], 'file', 'skipOnEmpty' => false, 'extensions' => 'php'],
];
}
public function upload()
{
/*
if ($this->validate()) {
$this->tplFile->saveAs('mail/views' . $this->tplFile->baseName . '.' . $this->tplFile->extension);
return true;
} else {
return false;
}
*/
//store using filesystem
$this->tplfilename->saveAs('../mail/views/' . $this->tplfilename->baseName . '.' . $this->tplfilename->extension);
return true;
}//end of upload function
public function attributeLabels()
{
return [
'id' => 'ID',
'tplfilename' => 'File name',
];
}
}
?>
I would like to have your comments about how to achieve to upload the file and record the filename on the data table, most of the issue is about this line: $model->save().
Here is my model like an example:
/*
* Upload image
* #params $url Url where to upload
* #return filename
*/
public function upload($url, $image_name)
{
try{
if ($this->validate()) {
$this->imageFile->saveAs($url . $this->imageFile->baseName . '.' . $this->imageFile->extension);
if($image_name){
FileHelper::unlink($url . $image_name);
}
return $this->imageFile->baseName . '.' . $this->imageFile->extension;
}
} catch (Exception $ex) {
throw new Exception("Error while upload file.");
return false;
}
Here is my controller:
/**
* Upload image for product.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
protected function Upload(UploadedFile $object, $name = null)
{
$user_id = $this->getUser()->id;
$model = new UploadForm();
$model->imageFile = $object;
$path = Yii::getAlias('#frontend/uploads/user-files/user-') . $user_id;
//check if dirrectory exist
if ( ! is_dir($path)) {
FileHelper::createDirectory($path);
}
$url = $path . '/';
return $model->upload($url, $name);
}
and here i call my method from action and save the model:
$cart_item_option->option_type_value = $this->Upload(UploadedFile::getInstanceByName('image'), null);
$cart_item_option->save();
Following code just uploads one file instead several files.
Any ideas, how to fix that?
Here is my model:
<?php
//Code programmed by Thomas Kipp
//Change it, learn it, do as u please!
///path:/models/
namespace frontend\models;
use Yii;
use yii\base\Model;
class myScriptForm extends Model{ // A new Class programmed by Thomas Kipp
...
public $avatar;
...
public function rules() {
$avatar=array();
return [
['avatar[]','file']]
}
}
//End of class
?>
Here is my method of SiteController:
public function actionScript() { //A new method, programmed by Thomas Kipp
$model = new myScriptForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->avatar = UploadedFile::getInstances($model, 'avatar[]');
if ($model->avatar) {
echo "<font size='4'><br><center>File <font color='red'> "
. "$model->avatar<font color='black'> successfully uploaded."
. "<br>It's available in folder 'uploadedfiles' </font></font color></center>";
$model->avatar->saveAs(Yii::getAlias('#uploadedfilesdir/' . $model->avatar->baseName . '.' . $model->avatar->extension));
} else
echo"<font size='4'><br><center>No Upload-file selected.<br>"
. "Nothing moved into folder 'uploadedfiles' </font></center>";
return $this->render('myScript', ['model' => $model]);
}
else {
return $this->render('myScript_Formular', ['model' => $model]);
}
}
and still my Formular, which is not uploading several files:
<?=
$form->field($model,'avatar[]')->widget(FileInput::classname(), ['options' => ['accept' => 'image/*', 'multiple' => true],])
?>
First of all, if you have something like echo (...) in controller - youre doing something wrong.
In your code youre not doing any foreach over uploaded files, so it's saving only one.
Yii2 - Uploading Multiple Files - here you have full guide how to upload multiple files, with examples etc.
Below code works for me, hope this will help you,
View file =>
<?= $form->field($model, 'image_files[]')->fileInput(['multiple' => true,'accept' => 'image/*']) ?>
Controller =>
$imagefiles = UploadedFile::getInstances($model, 'image_files');
$model->image_files = (string)count($imagefiles);
if (!is_null($imagefiles)) {
$dirpath = dirname(getcwd());
foreach ($imagefiles as $file) {
$productimage = new ProductImages();
$productimage->image_name = '/admin/uploads/'.$file->baseName.'.'.$file->extension;
$productimage->product_id = $model->id;
if ($productimage->save()) {
$file->saveAs($dirpath . '/admin/uploads/' . $file->baseName . '.' . $file->extension);
}
}
}
I have yii2 application using advanced template and database mySql, i already make function for import an excel file to one of the table,
I made the function in a controller named student that contains CRUD of students data.this is my code
public function actionImportExcel()
{
$inputFile = 'uploads/siswa_file.xlsx';
try{
$inputFileType = \PHPExcel_IOFactory::identify($inputFile);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch (Exception $e) {
die('Error');
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for($row=1; $row <= $highestRow; $row++)
{
$rowData = $sheet->rangeToArray('A'.$row.':'.$highestColumn.$row,NULL,TRUE,FALSE);
if($row==1)
{
continue;
}
$siswa = new Siswa();
$siswa->nis = $rowData[0][0];
$siswa->nama_siswa = $rowData[0][1];
$siswa->jenis_kelamin = $rowData[0][2];
$siswa->ttl = $rowData[0][3];
$siswa->alamat = $rowData[0][4];
$siswa->telp = $rowData[0][5];
$siswa->agama = $rowData[0][6];
$siswa->nama_ortu = $rowData[0][7];
$siswa->telp_ortu = $rowData[0][8];
$siswa->pekerjaan_ortu = $rowData[0][9];
$siswa->tahun_masuk = $rowData[0][10];
$siswa->kelas = $rowData[0][11];
$siswa->save();
print_r($siswa->getErrors());
}
die('okay');
}
but i don't know how to make a button in a view to make this function work. i mean i want to make a button that when the user click the button and browse their excel file they can import that file and the data inside the excel can import to database
First you should upload the file
and then processing with your function
there are several parts of code you must produce ..
eg a view for the user to upload the file
View: #app/views/site/upload.php
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
Controller: #app/controllers/SiteController.php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('upload', ['model' => $model]);
}
}
Model: #app/models/UploadForm.php
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('uploads/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
}
the code is from this doc
I am writing code in php to basically 'map' data from a mySQL database to another database. I am using the code as follows:
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
however, I am getting an error:
syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Everywhere I look this seems to be the correct syntax. Is there something I'm missing here?
I tried putting the controller in there as well $this->controllerName->query, but that didn't work either.
Full Code:
class CaExtraFlowsheetFields extends CaBase {
public $name = 'CaExtraFlowsheetFields';
/*
NOTE: This is to take all the fields in flowsheet and
maps their id's.
*/
//public $useTable = 'ANSWER_ENTRY';
public $useTable = 'PATIENT_FLOWSHEET_DATA';
public $primaryKey = 'PT_FS_DATA_ID';
protected function getPrimaryKeyValue(
$hospital_id,
$patient_id,
$admission_id = null
) {
return $patient_id;
}
//*CHANGE BEGIN*
$results = $this->query("select PT_FS_DATA_ID from PATIENT_FLOWSHEET_DATA where
DT_LAST_UPDATED_TIME = (select top 1 DT_LAST_UPDATED_TIME from PATIENT_FLOWSHEET_DATA
order by DT_LAST_UPDATED TIME desc) group by PT_FS_DATA_ID;");
protected $filedMethodMappings = array(
'Method_GO' => array(
CaBase::KEY_MAPPING_LOGIC_COMPLEXITY => CaBase::LEVEL2_COMPLEXITY,
CaBase::KEY_FIELD_LOGIC_NAME => 'wsMethod_GO',
);
//########################################################################//
//Note[]>Block[] //
//>Method that calls LookUpField for every field in flowsheet // //
//########################################################################//
public function wsMethod_GO ($params) {
foreach($results as $value){
$questionName = ''.$value;
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "arrivez-vouz" ;
$ret = $this->wsLookUpField($params,$questionName,$msg_prefix);
return $ret;
}
unset($value);
}
//########################################################################//
public function wsLookUpField($params,$questionName,$msg_prefix){
$arrayValues=array();
try{
$hospital_id = $params[Constants::KEY_HOSPITAL_ID];
$patient_id = $params[Constants::KEY_PATIENT_ID];
$admission_id = $params[Constants::KEY_ADMISSION_ID];
$msg_prefix = $this->name . "::" . __FUNCTION__ . ": ". "attendez-vouz: l'hopital= ".$hospital_id.
" patient= ".$patient_id." admission= ".$admission_id;
//shows info about given question name
$msg_prefix = "*!*!*!*Show me ---> ".$questionName." : ".$answer_entry_id.
" = aic: " .$answer_id_check;
$ret = array();
//now with needed fields, grab the A_NAME:
$params = array(
'conditions' => array(
$this->name . '.PID' => $patient_id,
$this->name . '.PT_FS_DATA_ID' => $questionName,
),
'order' => array(
$this->name . '.' . $this->primaryKey . ' DESC'
),
'fields' => array(
$this->name . '.FS_VALUE_TEXT',
)
);
$rs = $this->find('first', $params);
/* check to make sure $rs has received an answer from the query
and check to make sure this answer is a part of the most recent
database entries for this note */
if (false != $rs) {
try {
$msg = $msg_prefix . "Data obtained successfully."."<br>".$result;
$result = $rs;
$ret = WsResponse::getResponse_Success($msg, $result);
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
/*answer was not part of most recent database entries, meaning no
answer was given for this particular question the last time this
particular note was filled out. Message is given accordingly.*/
} else {
$msg = $msg_prefix . "/No answer given.";
$ret = WsResponse::getResponse_Error($msg);
}
} catch (Exception $e) {
$msg = $msg_prefix . "Exception occurred.";
$ret = WsResponse::getResponse_Error($msg);
}
return $ret;
}
Here is what you are doing:
class ABC {
$result = 'whatever';
}
You can't declare a variable there!
Code needs to be inside a method/function...
class ABC
{
public function wsMethod_GO ($params)
{
$result = 'whatever';
}
}