mumunotes

  • Home
  • Contact Us

Saturday, 13 June 2015

Upload File or Image on Yii2

 mumunotesss     12:06     Yii, Yii2     No comments   

Assalamualaikum Wr. Wb. Good afternoon all. In this session, I would like to explain upload file or image on Yii2 application. Now, i use default Yii2 upload file.
I still using yii2basic application that created before. If you haven't develop that, please prefer this link to develop.
First, plase running this query or add fields foto to your mahasiswa table :

alter table mahasiswa add foto varchar(50);
Then, create uploads direcoty on yii2basic/web for save the file upload.
Second, please open your Mahasiswa model class and change with following the content :
namespace app\models;
use Yii;
class Mahasiswa extends \yii\db\ActiveRecord{
 public function rules()
    {
        return [
          [['foto'],'required','on' => 'create'],
          [['foto'],'file','extensions'=>'jpg, jpeg, png', 'maxSize'=>1024 * 1024 * 1],
        ];
    }

 public function attributeLabels()
    {
        return [
            'foto' => 'Foto',
        ];
    }
}
Third, open your MahasiswaController class in controllers directory and change with following the content :
use Yii;
use yii\web\UploadedFile;
class MahasiswaController extends Controller{

 //another code
 public function actionCreate()
    {
        $model = new Mahasiswa(['scenario' => 'create']);

        if ($model->load(Yii::$app->request->post())) {
            try{
               $picture = UploadedFile::getInstance($model, 'foto');
               $model->foto = $_POST['Mahasiswa']['nim'].'.'.$picture->extension;
               if($model->save()){
                   $picture->saveAs('uploads/' . $model->nim.'.'.$picture->extension);
                   Yii::$app->getSession()->setFlash('success','Data saved!');
                   return $this->redirect(['view','id'=>$model->nim]);
               }else{
                   Yii::$app->getSession()->setFlash('error','Data not saved!');
                   return $this->render('create', [
                         'model' => $model,
                   ]);
               }
          }catch(Exception $e){
              Yii::$app->getSession()->setFlash('error',"{$e->getMessage()}");
          }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
 //another code

}
Fourd, open your _form file in views/mahasiswa directory and change with following the content:
$form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]);
 
//another code

echo $form->field($model, 'foto')->fileInput();

//another code
For displaying the picture on DetailView, please following the content :
echo DetailView::widget([
        'model' => $model,
        'attributes' => [
            'nim',
            'nama',
            'jurusan',
            'angkatan',
            'alamat:ntext',
            [
                 'label'=>'Foto',
                 'format'=>'raw',
                 'value'=>Html::img(Yii::$app->request->baseUrl.'/uploads/'.$model->foto,['width'=>'100px']),
           ],
        ],
    ]);
Ok, you finished this code. And then you must trial yii2basic application. Access your yii2basic, and you trial create new data.



If you found error message "The fileinfo PHP extension is not installed" on your application, please actived php_fileinfo extensions on php.ini and restart your apache.
Now, you have been implemented file upload to your Yii2 application. I hope my tutorial can help you anymore. So good luck. Thank you. Wassalamualaikum Wr. Wb.
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

About Me

mumunotesss
View my complete profile

Popular Posts

  • Change password with validation and repeat password on Yii2
    Hello everybody. I could not post an article because I didn't have new knowledge to share. Ok, this day I will share about "...
  • Import Data from CSV File to Database Without Extension in Yii2
    Hello everybody, Assalamualaikum Wr. Wb. Nearly 1 month I don't publish article. Now, I publish an article about " Import Data fro...
  • Membuat login Yii2 dengan Database
    Selamat pagi guys. Sorry beberapa hari kamaren sibuk. Jadi belum sempet update blog lagi. Mumpung kali ini sempet, hari ini mau berbagi te...
  • Membuat fungsi CRUD dengan Gii Yii2
    Selamat pagi guys. Setelah kemaren kita membuat login dari database, hari ini kita akan membuat CRUD (create, read, update, delete) dengan ...

Blog Archive

  • ▼  2015 (16)
    • ►  November (1)
    • ►  September (1)
    • ►  August (1)
    • ▼  June (8)
      • Upload File or Image on Yii2
      • Implementation google reCAPTCHA on Yii2 Applicati...
      • Implementation Captcha on Yii2
      • Change password with validation and repeat passwor...
      • Membuat Alert atau Notifikasi di Yii2
      • ACF (Access Control Filter) Yii2 dengan Role dari ...
      • Membuat fungsi CRUD dengan Gii Yii2
      • Membuat login Yii2 dengan Database
    • ►  May (5)

Translate

Copyright © mumunotes
Distributed By My Blogger Themes | Blogger Theme By NewBloggerThemes