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);
}
}
}
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();
I'm creating an endpoint for a mobile application to send a image to the server. I'm posting the image with the POSTMAN extension for chrome. The image is in the $_FILES variable, and named image. How can I load this image into a model, or the UploadedFile class? The $model->load(Yii::$app->request->post()) line does not correctly load the file, as it is not in Yii2's naming convention for forms.
It's currently returning:
{
"success": false,
"message": "Required parameter 'image' is not set."
}
Code
models\Image.php
<?php
namespace api\modules\v1\models;
use yii\base\Model;
use yii\web\UploadedFile;
class Image extends Model
{
/**
* #var UploadedFile
*/
public $image;
public function rules()
{
return [
[['image'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
$path = dirname(dirname(__FILE__)) . '/temp/';
if ($this->validate()) {
$this->image->saveAs($path . $this->image->baseName . '.' . $this->image->extension);
return true;
} else {
die(var_dump($this->errors));
return false;
}
}
}
controllers\DefaultController.php
<?php
namespace api\modules\v1\controllers;
use api\modules\v1\models\Image;
use yii\web\Controller;
use yii\web\UploadedFile;
use Yii;
class DefaultController extends Controller
{
public $enableCsrfValidation = false;
public function actionIndex()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = new Image();
if (Yii::$app->request->isPost) {
if($model->load(Yii::$app->request->post()))
{
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->upload()) {
// file is uploaded successfully
return ['success' => true, 'message' => 'File saved.'];
}
else return ['success' => false, 'message' => 'Could not save file.'];
}
else return ['success' => false, 'message' => 'Required parameter \'image\' is not set.'];
}
else return ['success' => false, 'message' => 'Not a POST request.'];
}
}
Postman
Your problem seems to be the name you are using to send the image file. Usually Yii2 uses names for form attributes like "ModelName[attributeName]" and you are sending your image file with the name "image"
There are 2 ways of fixing this:
Change the name you use to send your image file to follow the same naming conveniton. However you don't seem to want that.
Use getInstanceByName('image') method instead of getInstance($model, 'image')
The problem come here
When you send files via api they are not sent asynchronously. If you check
echo '<pre>';
print_r($_FILES); //returns nothing
print_r($_POST["image"]); //returns something
echo '</pre>';
die;
One reason is that your controller extendsyii\web\controller which is not used by rest apis, extend yii\rest\controller
The other way to go about this is by using javascript formData when sending the post request
This is a way i handled a previous ajax post of an image probably itll give you a guideline
The form
<?php $form = ActiveForm::begin(['options' => ['enctype' =>
'multipart/form-data','id'=>'slider_form']]); ?> //dont forget enctype
<?= $form->field($model, 'file')->fileInput() ?>
Then on the ajax post
var formData = new FormData($('form#slider_form')[0].files);
$.post(
href, //serialize Yii2 form
{other atributes ,formData:formData}
)
Then on the controller simply access via
$model->file =$_FILES["TblSlider"]; //here this depends on your form attributes check with var_dump($_FILES)
$file_tmp = $_FILES["TblSlider"]["tmp_name"]["file"];
$file_ext = pathinfo($_FILES['TblSlider']['name']["file"], PATHINFO_EXTENSION);
if(!empty($model->file)){
$filename = strtotime(date("Y-m-d h:m:s")).".".$file_ext;
move_uploaded_file($file_tmp, "../uploads/siteimages/slider/".$filename);
///move_uploaded_file($file_tmp, Yii::getAlias("#uploads/siteimages/slider/").$filename);
$model->image = $filename;
}
I hope this helps
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
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]);