Yii2 kartik file FileInput Multiple - yii2

So I am working with Yii2 and am fairly new to it. I am using Kartik File upload and have attempted to convert the code for multiple files. but it only saves the first file.
I have removed the validation as this was also failing but will add back in once I know all else is working.
Model:
/**
* Process upload of image
*
* #return mixed the uploaded image instance
*/
public function uploadImage() {
// get the uploaded file instance. for multiple file uploads
// the following data will return an array (you may need to use
// getInstances method)
$image = UploadedFile::getInstances($this, 'image');
foreach ($image as $images) {
// if no image was uploaded abort the upload
if (empty($images)) {
return false;
}
// store the source file name
$this->image_src_filename = $images->name;
$extvar = (explode(".", $images->name));
$ext = end($extvar);
// generate a unique file name
$this->image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the uploaded image instance
return $images;
} }
Controller:
/**
* Creates a new PhotoPhotos model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new PhotoPhotos();
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$images = $model->uploadImage();
if ($model->save(false)) {
// upload only if valid uploaded file instance found
if ($images !== false) {
$path = $model->getImageFile();
$images->saveAs($path);
}
return $this->redirect(['view', 'id' => $model->ID]);
} else {
//error in saving
}
}
return $this->render('create', [
'model' => $model,
]);
}
View:
//uncomment for multiple file upload
echo $form->field($model, 'image[]')->widget(FileInput::classname(), [
'options'=>['accept'=>'image/*', 'multiple'=>true],
]);

I see one problem which is that you reversed $images and $image in
foreach ($image as $images)
which should be
foreach ($images as $image)
Cheers

Related

How do i save files in a dyanamic location in PHP Yii2?

I want to save files to directories based on company id like if company has id of 11 then it should create a folder of same name and save/upload the files there?
I have my controller logic here but i dont know how to pass my company id which is in Company Model to saveAs() function.
Scene: I have list of companies from different model and i want to create a directory according to company id/name where the respective layout gets saved.
public function actionCreate()
{
$company=Company::find()->all();
$model = new Layouts();
// if ($model->load(Yii::$app->request->post()) && $model->save()) {
// return $this->redirect(['view', 'id' => $model->layout_id]);
// }
$model->setScenario('create');
if ($model->load(Yii::$app->request->post())) {
$model->layouts=UploadedFile::getInstance($model,'layouts');
if(!empty($model->layouts)){
$filename=time()."_layouts".".". $model->layouts->extension;
$model->layouts->saveAs('#app/web/uploads/layouts/'.$filename); //here i want it to be #app/web/uploads/layouts/company-id/filename
$model->layouts=$filename;
$model->created_by=Yii::$app->user->id;
$model->updated_by=Yii::$app->user->id;
}else{
var_dump($model->errors);die;
}
if($model->save()){
Yii::$app->session->addFlash('success','Record Created Successfully');
return $this->redirect(['view','id'=>$model->id]);
}else{
Yii::$app->session->addFlash('error','Record Can not be Created ');
}
return $this->render('create', [
'model' => $model,
'company'=>$company
]);
}
}
You should create folder first,
\yii\helpers\FileHelper::createDirectory(\Yii::getAlias('#app/web/uploads/layouts/'.$model->id), 0777);

Upload a file to filesystem and then store details on a datatable [duplicate]

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();

Make FileInput Optional for user in Yii2

I have a file Input field in my form which works good to upload the file. But I want to keep the provision for user that they might not upload any file at all.
My Code looks like below -
Model Rule -
[['jha'],'file','skipOnEmpty' => true,'extensions' => 'pdf'],
Form
<?= $form->field($model, 'jha')->fileInput(['accept' => 'application/pdf']); ?>
Controller -
public function actionCreatenewworkbasic()
{
$model = new Workpermit();
$model->wp_timeissued = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post()))
{
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}else{
return $this->renderAjax('createnewworkbasic', [
'model' => $model,
]);
}
}
By this code, If I leave the upload field untouched, I get error -
Call to a member function saveAs() on null
Check empty before saveAs()
if ($model->load(Yii::$app->request->post())) {
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}

Yii2 POST image to model in API without Yii2 Naming convention

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

How to upload files in web folder in yii2 advanced template?

I try to upload files in backend and each time i uploaded a file it was successfully uploaded and successfully saved in the DB but it wasn't save to the directory i specified so my application can't find the file, and i already gave 777 permission to the uploads folder in web directory. below is my codes
Model to handle and save the file upload...
How to upload files in root folder in yii2 advanced template?
Model responsible for the upload
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
class UploadForm extends Model {
public $img;
public $randomCharacter;
public function rules(){
return[
[['img'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg'],
];
}
public function upload(){
$path = '/uploads/';
$randomString = '';
$length = 10;
$character = "QWERTYUIOPLKJHGFDSAZXCVBNMlkjhgfdsaqwertpoiuyzxcvbnm1098723456";
$randomString = substr(str_shuffle($character),0,$length);
$this->randomCharacter = $randomString;
if ($this->validate()){
$this->img->saveAs($path .$randomString .'.'.$this->img->extension);
return true;
}else{
return false;
}
}
}
The product model reponsible for save info into database
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use yii\Validators\FileValidator;
class Products extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'products';
}
public function rules()
{
return [
[['name'], 'string', 'max' => 100],
[['descr', 'img', 'reviews'], 'string', 'max' => 255],
// [['file'], 'file', 'skipOnEmpty' => false, 'extensions'=> 'png, jpg,jpeg']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'img' => 'Img',
];
}
}
my controller and the action
public function actionCreate()
{
$time = time();
$model = new Products();
$upload = new UploadForm();
if ($model->load(Yii::$app->request->post()) ) {
//get instance of the uploaded file
$model->img = UploadedFile::getInstance($model, 'img');
//define the file path
$upload->upload();
//save the path in the db
$model->img = 'uploads/' .$upload->randomCharacter .'.'.$model->img->extension;
$model->addtime = $time;
$model->save();
return $this->redirect(['view', 'product_id' => $model->product_id]);
}else {
return $this->render('create', [
'model' => $model,
]);
}
}
and my view file has been modified too thanks for any help
$path = '/uploads/';
That means you are uploading files to /uploads, the top level folder in the system.
Run cd /uploads in your terminal and check, most likely files were uploaded there.
To fix that, you need to specify correct full path. The recommended way to do it is using aliases.
In case of advanced application, you already have #backend alias, so you can use it:
$this->img->saveAs(\Yii::getAlias("#backend/web/uploads/{$randomString}.{$this->img->extension}");
Or create your own alias in common/config/bootstrap.php:
Yii::setAlias('uploads', dirname(dirname(__DIR__)) . '/backend/web/uploads');
And then use it like this:
Yii::getAlias('#uploads');
Don't forget to include use Yii if you are not in root namespace or use \Yii;
If you want your images to be accessible on frontend, you can create symlink between frontend and backend images folders.