Home PHP Framework YII How to upload pictures in yii2

How to upload pictures in yii2

Dec 07, 2019 pm 04:20 PM
yii2 upload image

How to upload pictures in yii2

The first step: Build the basic work of uploading. For details, please see: http://www.yiichina.com/tutorial/328

The second step: Build the website A product table with fields id, name, picurl.

Step 3: GII generates PRODUCT models, classes, and views.

Step 4:

main.css 放在frontend\web\css
.onedialog{position:absolute; left: 300px; top: 500px; z-index: 10; width: 700px; height: 400px;border
-radius:5px;
box-shadow:5px 2px 6px #000; border: 2px solid #666}
.oneiframe{ width: 100%; height: 100% }
Copy after login

main.js is placed in frontend\web\assets

$(function(){
$('#product-picurl').click(function(){
$('#oneupload').remove();
$(&#39;<div>&#39;).appendTo($(&#39;body&#39;)).attr({"class":"onedialog",&#39;id&#39;:"oneupload"});
$(&#39;<iframe>&#39;).appendTo($(&#39;#oneupload&#39;)).attr({"src":"?r=upload","class":"oneiframe"})
});
    var v=$(&#39;#product-picurl&#39;).val();
if(v){
$(&#39;<img>&#39;).attr({"src":v,"style":"height:50px"}).insertAfter($(&#39;#product-picurl&#39;));
}
});
Copy after login

Then register these two files in frontend\assets\AppAsset.php

class AppAsset extends AssetBundle
{
    public $basePath = &#39;@webroot&#39;;
    public $baseUrl = &#39;@web&#39;;
    public $css = [
        &#39;css/site.css&#39;,
        &#39;css/main.css&#39;,
    ];
    public $js = [
        &#39;assets/main.js&#39;
    ];
    public $depends = [
        &#39;yii\web\YiiAsset&#39;,
        &#39;yii\bootstrap\BootstrapAsset&#39;,
    ];
}
Copy after login

UploadController.php

<?PHP
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class UploadController extends Controller
{
    public function actionIndex()
    {
        $model = new UploadForm();
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, &#39;file&#39;);
            if ($model->file && $model->validate()) {
                //$model->file->saveAs(&#39;uploads/&#39; . $model->file->baseName . &#39;.&#39; .$model->
                file->extension); 
                $fileName=&#39;uploads/&#39; . date("YmdHis") . &#39;.&#39; . $model->file->extension;
                $model->file->saveAs($fileName);
            }
            echo "<script src=&#39;assets/upload.js&#39;></script>;";
            echo "<script>";
            echo "var oneinput=parent.document.getElementById(&#39;product-picurl&#39;);";
            echo "parent.document.getElementById(&#39;product-picurl&#39;).value=&#39;".$fileName."&#39;;";
            echo "var oneupload = parent.document.getElementById(&#39;oneupload&#39;);";
            echo "var img = document.createElement(&#39;img&#39;);";
            echo "img.setAttribute(&#39;style&#39;, &#39;height:50px&#39;);";
            echo "img.src =&#39;".$fileName."&#39;;";
            echo "insertAfter(img,oneinput);";
            echo "oneupload.parentNode.removeChild(oneupload)";
            echo "</script>";
        }
        return $this->render(&#39;upload&#39;, [&#39;model&#39; => $model]);
    }
}
?>
Copy after login

UploadForm.php

<?PHP
namespace app\models;
use yii\base\Model;
use yii\web\UploadedFile;
/**
 * UploadForm is the model behind the upload form.
 */
class UploadForm extends Model
{
    /**
     * @var UploadedFile file attribute
     */
    public $file;
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [[&#39;file&#39;], &#39;file&#39;],
        ];
    }
}
?>
Copy after login

upload.php

<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin([&#39;options&#39; => [&#39;enctype&#39; => &#39;multipart/form-data&#39;]]) ?>
<?= $form->field($model, &#39;file&#39;)->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>
Copy after login

PHP Chinese website has a large number of free Yii introductory tutorials, everyone is welcome to learn!

The above is the detailed content of How to upload pictures in yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set the yii frame timestamp tutorial How to set the yii frame timestamp tutorial Mar 06, 2025 pm 02:18 PM

This tutorial demonstrates Yii Framework's timestamp management. It details using TimestampBehavior for automatic created_at and updated_at updates, offering customization options and comparing it to manual updates, database triggers, and custom be

What Are the Best Practices for Using Yii in a Cloud-Native Environment? What Are the Best Practices for Using Yii in a Cloud-Native Environment? Mar 18, 2025 pm 04:39 PM

The article discusses best practices for deploying Yii applications in cloud-native environments, focusing on scalability, reliability, and efficiency through containerization, orchestration, and security measures.

Comparison of Yii and Laravel frameworks What is the difference between Yii and Laravel frameworks Comparison of Yii and Laravel frameworks What is the difference between Yii and Laravel frameworks Mar 06, 2025 pm 02:17 PM

This article compares the PHP frameworks Yii and Laravel. Yii prioritizes speed and structure, while Laravel emphasizes developer experience and flexibility. Though both handle large-scale applications, Yii offers superior raw performance, while La

How about yii framework? What is yii framework How about yii framework? What is yii framework Mar 06, 2025 pm 02:20 PM

This article introduces Yii, a high-performance PHP framework ideal for large-scale web applications. It highlights Yii's speed, security, and robust architecture (MVC), emphasizing its advantages over other frameworks like Laravel, Symfony, and Cod

Pros and cons of yii framework Pros and principles of yii framework Pros and cons of yii framework Pros and principles of yii framework Mar 06, 2025 pm 02:22 PM

This article analyzes Yii framework's strengths and weaknesses. It highlights Yii's high performance, robust security, rapid development capabilities, and extensibility, but also notes a steeper learning curve and potential complexity for smaller pr

Which is better between Yii framework and TP framework? The difference between Yii framework and TP framework Which is better between Yii framework and TP framework? The difference between Yii framework and TP framework Mar 06, 2025 pm 02:21 PM

This article compares Yii and ThinkPHP (TP) frameworks. The choice depends on project scale and developer experience. Yii, robust and mature, suits large, complex projects needing high performance. TP, simpler and faster for development, is better f

How to call public functions yii How to call public functions yii Tutorial How to call public functions yii How to call public functions yii Tutorial Mar 06, 2025 pm 02:23 PM

This article details how to call and organize common functions in Yii applications. It advocates encapsulating functions within classes, ideally in a dedicated app/helpers directory, for improved reusability and maintainability. Different approache

What Are the Key Considerations for Using Yii in a Serverless Architecture? What Are the Key Considerations for Using Yii in a Serverless Architecture? Mar 18, 2025 pm 04:33 PM

The article discusses key considerations for using Yii in serverless architectures, focusing on statelessness, cold starts, function size, database interactions, security, and monitoring. It also covers optimization strategies and potential integrati

See all articles