gpt4 book ai didi

php - 如何在yii中上传照片?

转载 作者:行者123 更新时间:2023-12-04 04:33:15 24 4
gpt4 key购买 nike

我无法在我的数据库和文件夹中上传照片...如果我使用 CModel 类来构建表单,同样的代码正在工作...但如果我使用纯 html,它会给我错误 Profilepic cannot be blank ...我的代码如下

我的表格

    <form method="post" action="<?php echo Yii::app()->getBaseUrl(true).'/index.php?r=user/create'?>" enctype="multipart/form-data">
<div class="row">
<label>Username</label><input type="text" name="username"/><span><?php if(isset($error['username'])) echo $error['username'][0]; ?></span>
</div>
<div class="row">
<label>Password</label><input type="password" name="password"/><span><?php if(isset($error['password'])) echo $error['password'][0]; ?></span>
</div>
<div class="row">
<label>Email</label><input type="text" name="email"/><span><?php if(isset($error['email'])) echo $error['email'][0]; ?></span>
</div>
<div class="row">
<label>Profile pic</label><input type="file" name="profilepic"/><span><?php if(isset($error['profilepic'])) echo $error['profilepic'][0]; ?></span>
</div>
<input type="hidden" value="No" name="flag"/>
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

我的 Controller 方法
   public function actionCreate()
{
$model=new User;

// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST))
{
$uploadedFile=CUploadedFile::getInstance($model,'profilepic');
$fileName = "{$uploadedFile}";
$model->profilepic = $fileName;
$model->attributes=$_POST;

if($model->save())
{
$a=$uploadedFile->saveAs(Yii::app()->basePath.'/../images/'.$fileName);
$this->redirect(array('create'));
}
}

$this->render('create',array(
'model'=>$model,
));
}

我的规则方法数组
     return array(
array('username, password,email,profilepic', 'required'),
array('email','email'),
array('profilepic','file','types'=>'jpg,jpeg,png'),
array('email','unique'),
array('username,password,email,flag,profilepic', 'safe', 'on'=>'search'),
);

有人可以帮我吗...

提前致谢

最佳答案

您需要更改 Controller 代码,例如遵循...

public function actionCreate()
{
$model=new User;
if(Yii::app()->request->isPostRequest) //change it
{
$model->profilepic=CUploadedFile::getInstanceByName('profilepic');
// $fileName = "{$uploadedFile}"; //this is not required
// $model->profilepic = $fileName; //this is also not required
$model->attributes=$_POST;

if($model->save())
{
$model->profilepic->saveAs(Yii::app()->basePath.'/../images/'.$model->profilepic);
$this->redirect(array('create'));
}
}

$this->render('create',array(
'model'=>$model,
));
}

最重要的是您需要进行的所有更改...我更改的最重要的一件事是 getInstanceByName('profilepic')

希望它可以解决您的问题..

关于php - 如何在yii中上传照片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20215370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com