本文整理汇总了PHP中CUploadedFile类的典型用法代码示例。如果您正苦于以下问题:PHP CUploadedFile类的具体用法?PHP CUploadedFile怎么用?PHP CUploadedFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CUploadedFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
/**
* @param \CActiveRecord $model
* @param string $attribute имя поля, содержащего CUploadedFile. В последствии этому полю будет присвоено имя файла изображения.
* @param \CUploadedFile $image
* @param array $sizes
*
* @throws \CException
*
* @return bool
*/
public function save(\CActiveRecord $model, $attribute = 'image', \CUploadedFile $image, $sizes = [])
{
$folderModel = $this->extractPath($model, $attribute, true);
if (!file_exists($folderModel)) {
mkdir($folderModel);
}
$imageExtension = isset($this->mimeToExtension[$image->getType()]) ? $this->mimeToExtension[$image->getType()] : 'jpg';
$imageId = $this->getRandomHash($model, $attribute);
$imagePathTemp = \Yii::getPathOfAlias('temp') . '/' . $imageId . '.' . $imageExtension;
if ($image->saveAs($imagePathTemp)) {
foreach ($sizes as $sizeName => $size) {
$folderModelAttribute = $this->extractPath($model, $attribute);
if (!file_exists($folderModelAttribute)) {
mkdir($folderModelAttribute);
}
$quality = array_key_exists('quality', $size) ? intval($size['quality']) : self::DEFAULT_QUALITY;
if ($quality <= 0 or $quality > 100) {
$quality = self::DEFAULT_QUALITY;
}
$pathImageSize = $folderModelAttribute . '/' . $imageId . '_' . $sizeName . '.' . $imageExtension;
if (array_key_exists('enabled', $size) and $size['enabled'] == false) {
if (array_key_exists('resave', $size) and $size['resave'] == false) {
rename($imagePathTemp, $pathImageSize);
} else {
$this->processor->open($imagePathTemp)->save($pathImageSize, ['quality' => $quality]);
}
} else {
$this->processor->open($imagePathTemp)->thumbnail(new Box($size['width'], $size['height']), (!isset($size['inset']) or $size['inset']) ? ImageInterface::THUMBNAIL_INSET : ImageInterface::THUMBNAIL_OUTBOUND)->save($pathImageSize, ['quality' => $quality]);
}
}
} else {
throw new \CException('can not save image');
}
return [self::KEY_ID => $imageId, self::KEY_EXT => $imageExtension];
}
示例2: saveMetaDataForUploadedFile
/**
* Save file meta data to persistent storage and return id.
*
* @param \CUploadedFile $uploadedFile uploaded file.
*
* @return integer meta data identifier in persistent storage.
*/
public function saveMetaDataForUploadedFile(\CUploadedFile $uploadedFile)
{
$ext = \mb_strtolower($uploadedFile->getExtensionName(), 'UTF-8');
$realName = pathinfo($uploadedFile->getName(), PATHINFO_FILENAME);
FPM::m()->getDb()->createCommand()->insert(FPM::m()->tableName, array('extension' => $ext, 'real_name' => $realName));
return FPM::m()->getDb()->getLastInsertID();
}
示例3: run
public function run()
{
$this->prepare();
if ($file = new CUploadedFile($this->md5($_FILES['file']['name']), $_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['size'], $_FILES['file']['error'])) {
if ($file->saveAs($this->basePath . $file->getName())) {
$this->append($file->getName());
}
}
}
示例4: changeLogo
public function changeLogo(CUploadedFile $uploadedFile)
{
$basePath = Yii::app()->getModule('cabinet')->getUploadPath();
//создаем каталог для аватарок, если не существует
if (!is_dir($basePath) && !@mkdir($basePath, 0755, true)) {
throw new CException(Yii::t('default', 'It is not possible to create directory for logos!'));
}
$filename = $this->id . '_' . time() . '.' . $uploadedFile->extensionName;
// обновить файл
//$this->removeOldLogo();
if (!$uploadedFile->saveAs($basePath . $filename)) {
throw new CException(Yii::t('default', 'It is not possible to save logos!'));
}
// получить запись лого
$photo = $this->with('photo')->find('photo.id=:id', [':id' => $this->logo_id]);
$webroot = Yii::getpathOfAlias('webroot');
$trimPath = str_replace($webroot, '', $basePath);
$logoFileOld = null;
$File = new File();
$File->model = 'Company';
$File->type = 'image';
$File->size = filesize($basePath . $filename);
$File->name = $filename;
$File->path = $trimPath . $filename;
$File->record_id = 0;
if (!is_null($photo['photo'])) {
$File->id = $photo['photo']['id'];
$File->isNewRecord = false;
$logoFileOld = $photo['photo']['path'];
}
if ($File->save()) {
if (0 != strcmp($logoFileOld, $File->path)) {
@unlink($webroot . $logoFileOld);
}
} else {
yii::log("changeLogo save FAILED id=[" . $File->id . "]", "info");
}
if ($this->logo_id != $File->id) {
// поменять logo_id
$this->logo_id = $File->id;
if ($this->validate(['logo_id'])) {
if (true === $this->update(['logo_id'])) {
} else {
Yii::log("changeLogo update logo_id FAILED", 'info');
}
} else {
Yii::log("changeLogo validate logo_id FAILED", 'info');
}
}
//$this->logo = $filename;
return true;
}
示例5: actionEdit
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
*/
public function actionEdit()
{
$model = $this->loadUser();
$profile = $model->profile;
// ajax validator
if (isset($_POST['ajax']) && $_POST['ajax'] === 'profile-form') {
echo UActiveForm::validate(array($model, $profile));
Yii::app()->end();
}
if (isset($_POST['User'])) {
$model->attributes = $_POST['User'];
$model->image = CUploadedFile::getInstance($model, 'image');
$profile->attributes = $_POST['Profile'];
if ($model->validate() && $profile->validate()) {
$model->save();
$profile->save();
Yii::app()->user->updateSession();
Yii::app()->user->setFlash('profileMessage', Yii::t('main', "Data saved successfully!"));
$this->redirect(array('/user/profile'));
} else {
$profile->validate();
}
}
$this->render('edit', array('model' => $model, 'profile' => $profile));
}
示例6: actionIndex
public function actionIndex($is_product = 1)
{
if (!empty($_POST)) {
$is_new_product = $is_product;
$images = CUploadedFile::getInstancesByName('images');
if (isset($images) && count($images) > 0) {
// go through each uploaded image
foreach ($images as $image => $pic) {
$model = new Slides();
$imageType = explode('.', $pic->name);
$imageType = $imageType[count($imageType) - 1];
$imageName = md5(uniqid()) . '.' . $imageType;
if ($pic->saveAs(Yii::getPathOfAlias('webroot') . '/upload/images/' . $imageName)) {
$model->image = $imageName;
$model->name = $pic->name;
$model->is_product = $is_new_product;
$model->save();
Yii::app()->user->setFlash('success', translate('Thêm thành công.'));
}
// handle the errors here, if you want
}
}
PIUrl::createUrl('/admin/slides/index', array('is_product' => $is_product));
}
$criteria = new CDbCriteria();
$criteria->addCondition("is_product= {$is_product}");
$criteria->order = 'id DESC';
$count = Slides::model()->count($criteria);
$pages = new CPagination($count);
// results per page
$pages->pageSize = 6;
$pages->applyLimit($criteria);
$model = Slides::model()->findAll($criteria);
$this->render('index', compact('model', 'pages'));
}
示例7: afterValidate
public function afterValidate($event)
{
$this->prepareDataDirectory();
$file = CUploadedFile::getInstanceByName($this->uploadInstance);
if ($file instanceof CUploadedFile && $file->getError() == UPLOAD_ERR_OK && !$this->Owner->hasErrors()) {
$uniqueFilename = P3StringHelper::generateUniqueFilename($file->getName());
$fullFilePath = $this->_fullDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
$relativeFilePath = $this->_relativeDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
if ($file->saveAs($fullFilePath)) {
#echo $fullFilePath;exit;
if (!$this->Owner->isNewRecord) {
$this->deleteFile($this->Owner->path);
}
if (!$this->Owner->title) {
$this->Owner->title = P3StringHelper::cleanName($file->name, 32);
}
$this->Owner->path = $relativeFilePath;
$this->Owner->mimeType = $file->type;
$this->Owner->size = $file->size;
$this->Owner->originalName = $file->name;
$this->Owner->md5 = md5_file($fullFilePath);
} else {
$this->Owner->addError('filePath', 'File uploaded failed!');
}
} else {
if ($this->Owner->isNewRecord) {
#$this->Owner->addError('filePath', 'No file uploaded!');
Yii::trace('No file uploaded!');
}
}
}
示例8: actionUpload
/**
* Upload file and process it for mapping.
*/
public function actionUpload()
{
// Get import post
$import = craft()->request->getRequiredPost('import');
// Get file
$file = \CUploadedFile::getInstanceByName('file');
// Is file valid?
if (!is_null($file)) {
// Determine folder
$folder = craft()->path->getStoragePath() . 'import/';
// Ensure folder exists
IOHelper::ensureFolderExists($folder);
// Get filepath - save in storage folder
$path = $folder . $file->getName();
// Save file to Craft's temp folder for later use
$file->saveAs($path);
// Put vars in model
$model = new ImportModel();
$model->filetype = $file->getType();
// Validate filetype
if ($model->validate()) {
// Get columns
$columns = craft()->import->columns($path);
// Send variables to template and display
$this->renderTemplate('import/_map', array('import' => $import, 'file' => $path, 'columns' => $columns));
} else {
// Not validated, show error
craft()->userSession->setError(Craft::t('This filetype is not valid') . ': ' . $model->filetype);
}
} else {
// No file uploaded
craft()->userSession->setError(Craft::t('Please upload a file.'));
}
}
示例9: actionUpdate
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Scodobjventascaract'])) {
$model->attributes = $_POST['Scodobjventascaract'];
// Verificar si existe un archivo que actualizar en la creacion
if (isset($_FILES) && $_FILES['Scodobjventascaract']['error']['imagen'] == 0) {
// Obtenemos la instancia del documento
$fDocumento = CUploadedFile::getInstance($model, 'imagen');
$sPathDocumento = $sPathFile . '/' . $model->id_cod_obj_venta . '/';
if (!file_exists($sPathDocumento)) {
mkdir($sPathDocumento, 0777, true);
}
$fDocumento->saveAs($sPathDocumento . $fDocumento->getName());
$model->imagen = $fDocumento->getName();
// $this->refresh();
}
if ($model->save()) {
$this->redirect(array('scodobjventas/' . $model->id_cod_obj_venta));
}
}
$this->render('update', array('model' => $model));
}
示例10: actionUpdate
public function actionUpdate()
{
$model = $this->loadModel($id);
if (isset($_POST['Avatars'])) {
$model->attributes = $_POST['Avatars'];
$model->icon = CUploadedFile::getInstance($model, 'icon');
if ($model->icon) {
$sourcePath = pathinfo($model->icon->getName());
$fileName = date('m-d') . Yii::app()->user->name . '.' . $sourcePath['extension'];
$model->image = $fileName;
}
if ($model->save()) {
//Если отмечен чекбокс «удалить файл»
if ($model->del_img) {
if (file_exists($_SERVER['DOCUMENT_ROOT'] . Yii::app()->urlManager->baseUrl . '/images/' . $model->image)) {
//удаляем файл
unlink('./images/' . $model->image);
$model->image = '';
}
}
//Если поле загрузки файла не было пустым, то
if ($model->icon) {
$file = './images/' . $fileName;
$model->icon->saveAs($file);
$image = Yii::app()->image->load($file);
$image->resize(100, 100);
$image->save();
}
$this->redirect(array('update', 'id' => $model->id));
}
}
$this->render('update', array('model' => $model));
}
示例11: actionCreate
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model = new MCompany();
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['MCompany'])) {
$model->attributes = $_POST['MCompany'];
$brandImage = CUploadedFile::getInstance($model, 'image_id');
if ($brandImage instanceof CUploadedFile) {
$image = new MImage();
$path_parts = pathinfo($brandImage->getName());
$file_name = time() . "." . $path_parts['extension'];
$path = Yii::app()->storagePath . "brand" . DIRECTORY_SEPARATOR . $file_name;
$brandImage->saveAs($path);
$image->created = time();
$image->path = "/storage/brand/" . $file_name;
$image->created_by = Yii::app()->user->id;
$image->save(false);
}
$model->image_id = $image->id;
$model->created = time();
$model->created_by = Yii::app()->user->id;
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array('model' => $model));
}
示例12: actionCreate
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model = new Photo();
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Photo'])) {
$model->attributes = $_POST['Photo'];
$picture_name = '';
$picture_file = CUploadedFile::getInstance($model, 'file');
$model->file = $picture_file;
if ($picture_file) {
$picture_name = $picture_file->name;
if (!is_dir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/')) {
mkdir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/');
}
if (!is_dir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/')) {
mkdir(Yii::getPathOfAlias('webroot') . '/themes/gallery-images/');
$picture_file->SaveAs(Yii::getPathOfAlias('webroot') . '/themes/gallery-images' . $picture_file->getName());
} else {
$picture_file->SaveAs(Yii::getPathOfAlias('webroot') . '/themes/gallery-images' . $picture_file->getName());
}
}
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->photo_id));
}
}
$this->render('create', array('model' => $model));
}
示例13: run
public function run()
{
$file = CUploadedFile::getInstanceByName('file');
$path = $this->getUniquePath($this->filesDir(), $file->extensionName);
$file->saveAs($path);
echo CHtml::link($file->name, "http://" . $_SERVER["HTTP_HOST"] . '/' . $path);
}
示例14: actionUpdate
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Partner'])) {
$model->attributes = $_POST['Partner'];
$model->fileLogo = CUploadedFile::getInstance($model, 'fileLogo');
if ($model->fileLogo) {
if ($model->validate(array('fileLogo'))) {
$fileName = $this->getAndSaveUploadedFile($model);
if ($fileName) {
if ($model->logo_path && file_exists($model->logo_path)) {
unlink($model->logo_path);
}
$model->logo_path = $fileName;
}
}
}
if ($model->save()) {
$this->redirect(array('admin'));
}
}
$this->render('update', array('model' => $model));
}
示例15: actionUpdate
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Slider'])) {
if (file_exists(Yii::app()->basePath . self::URLUPLOAD . $model->file_name)) {
unlink(Yii::app()->basePath . self::URLUPLOAD . $model->file_name);
}
$model->attributes = $_POST['Slider'];
$uploadedFile = CUploadedFile::getInstance($model, 'file_name');
$rnd = rand(0, 999999);
$wkt = date('m-d-Y-h-i-s', time());
$fileName = "{$wkt}_{$rnd}_{$uploadedFile}";
$model->file_name = $fileName;
$model->last_update = new CDbExpression('NOW()');
if ($model->save()) {
if ($uploadedFile !== null) {
$uploadedFile->saveAs(Yii::app()->basePath . self::URLUPLOAD . $model->file_name);
}
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('update', array('model' => $model));
}