几个月前,我使用YII开发了一个简单的应用程序,其中一个功能是上传文件。该功能在我的开发机器中运行良好,几天前,客户发现自部署以来,文件上传功能在他的服务器中不起作用。
在那之后,我测试了我的开发机器,但它也不工作。
我的控制器看起来:
public function actionEntry() {
if (!Yii::app()->user->isGuest) {
$model = new TrackForm;
if (isset($_POST['TrackForm'])) {
$entry = new Track;
try {
$entry->product_image = $_POST['TrackForm']['product_image'];
$entry->product_image = CUploadedFile::getInstance($model, 'product_image');
if ($entry->save()) {
if ($entry->product_image) {
$entry->product_image->saveAs($entry->product_image->name, '/trackshirt/uploads');
}
}
$this->render('success', array('model' => $model));
// redirect to success page
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "'n";
}
} else {
$this->render('entry', array('model' => $model));
}
}
}
型号如下:
<?php
class Track extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'product_details';
}
}
我的观点看起来:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'hide-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<p class="auto-style2"><strong>Administration - Add New Product</strong></p>
<table align="center" style="width: 650px"><td class="auto-style3" style="width: 250px">Product Image</td>
<td>
<?php echo $form->fileField($model, 'product_image'); ?>
</td>
</tr>
</table>
<p class="auto-style1">
<div style="margin-leftL:-100px;">
<?php echo CHtml::submitButton('Submit New Product Form'); ?>
</div>
<?php $this->endWidget(); ?>
知道问题出在哪里吗?我试着调试它,但每次它都返回Null。
谢谢。
此链接可能会对您有所帮助。还转储CUploadedFile实例以检查发生了什么。
我很惊讶你没有看到错误消息:
<?php echo $form->activeFileField($model, 'product_image'); ?>
因为CActiveForm没有属于CHtml 的方法activeFileField()
我想你需要
<?php echo $form->fileField($model, 'product_image'); ?>
在做出这个改变后,我可以使用你的代码在我的服务器上上传一个文件,其中删除了另一个右括号:
// redirect to success page
/*}*/
} catch (Exception $e) {
(可能是上传代码时剪切的产物)
$image = CUploadedFile::getInstance($model, 'product_image');
$entry->product_image = $image->name;