我已经关注yii网站使用上传图片,代码在这里:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs('path/to/localFile');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
但是如何通过currentdate + filename.png重命名文件并上传到路径,我还需要更新和删除代码。 非常感谢
我已经解决了这个问题:
public function currentDate(){
$date = date('m-d-Y-h-i-s', time());
return $date;
}
public function actionCreate(){
$model = new News();
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$uploadedFile = CUploadedFile::getInstance($model, 'images');
$fileName = "{$this->currentDate()}-{$uploadedFile}";
$model->images = $fileName;
if($model->save()){
$uploadedFile->saveAs("upload/".$fileName);
$this->redirect(array('news/index'));
}else{
$model = new News();
$this->render('create',
array('model' =>$model,
'result'=>'insert new fail !',
));
}
}else{
$this->render('create',
array(
'model'=>$model,
));
}
}
答案 0 :(得分:3)
public function actionCreate()
{
$model=new News;
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$name = $_FILES['News']['name']['images'];
$filename = pathinfo($name, PATHINFO_FILENAME);
$ext = pathinfo($name, PATHINFO_EXTENSION);
$newName = date("m-d-Y-h-i-s", time())."-".$filename.'.'.$ext;
$model->images = CUploadedFile::getInstance($model,'images');
if($model->save())
$fullImgSource = Yii::getPathOfAlias('webroot').'/upload/'.$newName;
$model->images->saveAs($fullImgSource);
$model->images = $newName;
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array('model'=>$model,));
}
答案 1 :(得分:1)
要在数据库中上传和更新后重命名文件,请尝试使用此代码。
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
if($model->save())
{
$imageName = @$_FILES["MenuItems"]["name"]["image"];
$uniqueName = (imageName . $model->id) . '.' . (end(explode('.', $imageName)));
$model->image=CUploadedFile::getInstance($model,'image');
$model->image->saveAs('path/to/localFile/'.$uniqueName);
$model->image = $uniqueName;
$model->save();
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
答案 2 :(得分:1)
您可以使用我之后创建的此方法上传文件并在上传之前更改其名称:
public static function createAttach($model, $imageAttrName) {
$model->$imageAttrName = CUploadedFile::getInstance($model, $imageAttrName);
$fecha = date('YmdHms');
if ($model->$imageAttrName) {
$attach_src = Yii::app()->basePath . '/../upload/' . $fecha.'.'.$model->$imageAttrName->getExtensionName(); //. '_' . $model->$imageAttrName;
$model->$imageAttrName->saveAs($attach_src);
$model->$imageAttrName = $fecha.'.'.$model->$imageAttrName->getExtensionName();// . '_' . $model->$imageAttrName;
}
}