첫 번째 단계: 업로드의 기본 작업 구축 자세한 내용은 http://www.yiichina.com/tutorial/328
을 참조하세요. #🎜🎜 #2단계: ID, 이름, picurl 필드가 포함된 제품 테이블을 만듭니다.3단계: GII는 PRODUCT 모델, 클래스 및 뷰를 생성합니다. 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% }
$(function(){ $('#product-picurl').click(function(){ $('#oneupload').remove(); $('<div>').appendTo($('body')).attr({"class":"onedialog",'id':"oneupload"}); $('<iframe>').appendTo($('#oneupload')).attr({"src":"?r=upload","class":"oneiframe"}) }); var v=$('#product-picurl').val(); if(v){ $('<img>').attr({"src":v,"style":"height:50px"}).insertAfter($('#product-picurl')); } });
class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css', 'css/main.css', ]; public $js = [ 'assets/main.js' ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
<?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, 'file');
if ($model->file && $model->validate()) {
//$model->file->saveAs('uploads/' . $model->file->baseName . '.' .$model->
file->extension);
$fileName='uploads/' . date("YmdHis") . '.' . $model->file->extension;
$model->file->saveAs($fileName);
}
echo "<script src='assets/upload.js'></script>;";
echo "<script>";
echo "var oneinput=parent.document.getElementById('product-picurl');";
echo "parent.document.getElementById('product-picurl').value='".$fileName."';";
echo "var oneupload = parent.document.getElementById('oneupload');";
echo "var img = document.createElement('img');";
echo "img.setAttribute('style', 'height:50px');";
echo "img.src ='".$fileName."';";
echo "insertAfter(img,oneinput);";
echo "oneupload.parentNode.removeChild(oneupload)";
echo "</script>";
}
return $this->render('upload', ['model' => $model]);
}
}
?>
<?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 [
[['file'], 'file'],
];
}
}
?>
<?php use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?> <?= $form->field($model, 'file')->fileInput() ?> <button>Submit</button> <?php ActiveForm::end() ?>
위 내용은 yii2에 사진을 업로드하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!