php yii-helpers-BaseFileHelper类(方法)实例源码

下面列出了php yii-helpers-BaseFileHelper 类(方法)源码代码实例,从而了解它的用法。

作者:rocketyan    项目:yii2-cm   
public function attachFile()
 {
     try {
         $model = $this->owner;
         $fileName = Inflector::slug($model->fullAddress) . '.pdf';
         $folder = $this->getModelSubDir() . '/';
         $model->pdf_path = $fileName;
         $pdf = new Pdf(['mode' => Pdf::MODE_UTF8, 'destination' => Pdf::DEST_FILE, 'content' => Yii::$app->view->render('@frontend/views/site/real-estate/print', ['model' => $model]), 'methods' => ['SetHeader' => ['Rapport ' . $model->fullAddress], 'SetFooter' => ['|Pagina {PAGENO}|']], 'filename' => Yii::getAlias('@uploadsBasePath') . "/files/{$folder}{$fileName}"]);
         $this->file = $pdf;
         BaseFileHelper::removeDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}");
         if (!BaseFileHelper::createDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}")) {
             throw new Exception(Yii::t('app', 'Failed to create the file upload directory'));
         }
         // Save and update model
         $pdf->render();
         $model->save();
         return true;
     } catch (yii\base\Exception $e) {
         return $e->getMessage();
     }
 }

作者:quynhv    项目:yii2-imagecach   
/**
  * @param $srcImagePath
  * @param bool $preset
  * @return string Path to cached file
  * @throws \Exception
  */
 private function createCachedFile($srcImagePath, $pathToSave, $size = null)
 {
     BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true);
     $size = $size ? $this->parseSize($size) : false;
     //        if($this->graphicsLibrary == 'Imagick'){
     $image = new \Imagick($srcImagePath);
     $image->setImageCompressionQuality(100);
     if ($size) {
         if ($size['height'] && $size['width']) {
             $image->cropThumbnailImage($size['width'], $size['height']);
         } elseif ($size['height']) {
             $image->thumbnailImage(0, $size['height']);
         } elseif ($size['width']) {
             $image->thumbnailImage($size['width'], 0);
         } else {
             throw new \Exception('Error at $this->parseSize($sizeString)');
         }
     }
     $image->writeImage($pathToSave);
     //        }
     if (!is_file($pathToSave)) {
         throw new \Exception('Error while creating cached file');
     }
     return $image;
 }

作者:md-nurul-isla    项目:simple-eco   
public function upload($upload_dir = 'product_image')
 {
     $file_name = [];
     if ($this->validate()) {
         $app_root = Yii::getAlias('@approot');
         $upload_path = "{$app_root}/uploads/{$upload_dir}/";
         if (!file_exists($upload_path)) {
             BaseFileHelper::createDirectory($upload_path, 0777, TRUE);
         } else {
             if (!is_dir($upload_path)) {
                 unlink($upload_path);
                 $this->upload($upload_dir);
             }
         }
         foreach ($this->imageFiles as $file) {
             $file_path = "{$upload_path}{$file->baseName}.{$file->extension}";
             $file->saveAs($file_path);
             $file_info['name'] = 'product_image';
             $file_info['type'] = $file->type;
             $file_info['value'] = $file->baseName . '.' . $file->extension;
             $file_name[] = $file_info;
         }
         return $file_name;
     } else {
         return false;
     }
 }

作者:sankam-nikoly    项目:yii2-kinopoisk-parse   
private function cacheDir()
 {
     $dir = Yii::getAlias(self::$cache_dir);
     if (!file_exists($dir)) {
         BaseFileHelper::createDirectory($dir, '0755');
     }
     return $dir;
 }

作者:denc    项目:resisto   
public static function delPhotos($sale_id)
 {
     $model = self::findAll(['sale_id' => $sale_id]);
     foreach ($model as $item) {
         $item->delete();
     }
     $path = Yii::$app->params['uploadSalePath'] . DIRECTORY_SEPARATOR . $sale_id;
     BaseFileHelper::removeDirectory($path);
 }

作者:Git111    项目:portfoli   
public function generateModul()
 {
     BaseFileHelper::createDirectory($this->moduleDirectory, 509, true);
     $content = $this->modulInner();
     $moduleFullName = $this->moduleDirectory . $this->moduleName . '.php';
     $myFail = fopen($moduleFullName, "w");
     fwrite($myFail, $content);
     fclose($myFail);
     return true;
 }

作者:cjtterabytesof    项目:yii2-adminlte-basi   
/** @inheritdoc */
 public function bootstrap($app)
 {
     /* Config Translation */
     if (!isset($app->get('i18n')->translations['adminlte*'])) {
         $app->get('i18n')->translations['adminlte*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
     }
     /* Config Theme */
     if (!isset($app->view->theme)) {
         $app->view->theme = new \yii\base\Theme(['pathMap' => ['@app/views/layouts' => '@cjtterabytesoft/adminlte/basic/views/layouts', '@app/views/site' => '@cjtterabytesoft/adminlte/basic/views/site']]);
     }
     /* Copy Avatar Images */
     if (\yii\helpers\BaseFileHelper::filterPath(\Yii::getAlias('@app/web/images'), $options = [])) {
         \yii\helpers\BaseFileHelper::copyDirectory(\Yii::getAlias('@cjtterabytesoft/adminlte/basic/images/'), \Yii::getAlias('@app/web/images'));
     }
     /* Config Params */
     if (!isset($app->params['adminEmail'])) {
         $app->params['adminEmail'] = 'admin@example.com';
     }
     if (!isset($app->params['AdminLTESkin'])) {
         $app->params['AdminLTESkin'] = 'skin-yellow';
     }
     if (!isset($app->params['Author'])) {
         $app->params['Author'] = '2015 - Wilmer Arambula';
     }
     if (!isset($app->params['Facebook_Account'])) {
         $app->params['Facebook_Account'] = 'https://www.facebook.com/username';
     }
     if (!isset($app->params['Google_Account'])) {
         $app->params['Google_Account'] = 'https://www.google.com/+username';
     }
     if (!isset($app->params['Linkedin_Account'])) {
         $app->params['Linkedin_Account'] = 'https://www.linkedin.com/in/username';
     }
     if (!isset($app->params['Twitter_Account'])) {
         $app->params['Twitter_Account'] = 'https://twitter.com/username';
     }
     if (!isset($app->params['WebName'])) {
         $app->params['WebName'] = 'My Application';
     }
     if (!YII_ENV_TEST) {
         if (!isset($app->params['imagesurl_30'])) {
             $app->params['imagesurl_30'] = 'http://www.basic.tk/images/avatar/profile/30/icon-avatar.png';
         }
         if (!isset($app->params['imagesurl_60'])) {
             $app->params['imagesurl_60'] = 'http://www.basic.tk/images/avatar/profile/60/icon-avatar.png';
         }
     } else {
         if (!isset($app->params['imagesurl_30'])) {
             $app->params['imagesurl_30'] = 'http://localhost.basic/images/avatar/profile/30/icon-avatar.png';
         }
         if (!isset($app->params['imagesurl_60'])) {
             $app->params['imagesurl_60'] = 'http://localhost.basic/images/avatar/profile/60/icon-avatar.png';
         }
     }
 }

作者:jatupon    项目:rgwe   
public function actionUpdate($id = null)
 {
     $model = new Article();
     if ($model->load(Yii::$app->request->post())) {
         $request = Yii::$app->request->post('Article');
         $id = $request['id'];
         if ($id) {
             $model = Article::findOne($id);
             $model->attributes = $request;
         }
         if ($model->save()) {
             $this->updateOrder('cid=' . $model->cid, '&langs=' . $model->langs);
             $files = \yii\web\UploadedFile::getInstances($model, 'upload_files');
             if (isset($files) && count($files) > 0) {
                 $mPath = \Yii::getAlias('@webroot') . '/images/article/news_' . $model->id;
                 if (!is_dir($mPath)) {
                     \yii\helpers\BaseFileHelper::createDirectory($mPath);
                 }
                 foreach ($files as $file) {
                     if ($request['cid'] == '12') {
                         $mPic = $file->baseName . '.' . $file->extension;
                     } else {
                         $mPic = 'nkc_' . substr(number_format(time() * rand(), 0, '', ''), 0, 14) . '.' . $file->extension;
                     }
                     //Upload Images
                     if ($file->saveAs($mPath . '/' . $mPic)) {
                         $image = \Yii::$app->image->load($mPath . '/' . $mPic);
                         $image->resize(1024, 1024);
                         $image->save($mPath . '/' . $mPic);
                         //resize images thumb
                         $image = \Yii::$app->image->load($mPath . '/' . $mPic);
                         $image->resize(250, 250);
                         $mThumb = $mPath . '/thumb/';
                         if (!is_dir($mThumb)) {
                             \yii\helpers\BaseFileHelper::createDirectory($mThumb);
                         }
                         $image->save($mThumb . $mPic);
                     }
                 }
             }
             return $this->redirect(array('index'));
         } else {
             print_r($model->getErrors());
             exit;
         }
     }
     if ($id) {
         $model = Article::findOne($id);
     } else {
         $sess = Yii::$app->session->get('sessArticle');
         $model->langs = $sess['langs'];
         $model->cid = $sess['cid'];
     }
     return $this->render('update', ['model' => $model]);
 }

作者:romka-che    项目:yii2-images-modul   
/**
  * @return static
  */
 public function flushPublishedCopies()
 {
     $module = $this->getModule();
     $subDirectory = $this->getSubDirectory();
     $dirToRemove = "{$module->publishPath}{$module->ds}{$subDirectory}";
     $quotedModelName = preg_quote($this->modelName, '/');
     if (preg_match("@{$quotedModelName}@", $dirToRemove)) {
         BaseFileHelper::removeDirectory($dirToRemove);
     }
     return $this;
 }

作者:dpodiu    项目:yii2-filemanager-aws   
public function getMimeType()
 {
     $extensions = $result = [];
     foreach ($this->acceptedFilesType as $mimeType) {
         $extensions[] = BaseFileHelper::getExtensionsByMimeType($mimeType);
     }
     foreach ($extensions as $ext) {
         $result = \yii\helpers\ArrayHelper::merge($result, $ext);
     }
     return $result;
 }

作者:cjtterabytesof    项目:yii2-adminlte-advance   
/** @inheritdoc */
 public function bootstrap($app)
 {
     /* Config Translation */
     if (!isset($app->get('i18n')->translations['adminlte*'])) {
         $app->get('i18n')->translations['adminlte*'] = ['class' => PhpMessageSource::className(), 'basePath' => __DIR__ . '/messages'];
     }
     /* Copy Avatar Images */
     if (\yii\helpers\BaseFileHelper::filterPath(\Yii::getAlias('@frontend/web/images'), $options = [])) {
         \yii\helpers\BaseFileHelper::copyDirectory(\Yii::getAlias('@cjtterabytesoft/adminlte/advanced/images/'), \Yii::getAlias('@frontend/web/images'));
     }
 }

作者:infoweb-internet-solution    项目:yii2-cm   
/**
  * Copies the image to the assets folder and save's it in the database.
  *
  * @param   string  $absolutePath   The path were the image is uploaded   
  * @param   bool    $isMain         A flag to determine if the image is the main image
  * @param   string  $identifier     The index that has to be set for the image in the database
  * @return  bool|Image
  * @throws  \Exception
  */
 public function attachImage($absolutePath, $isMain = false, $identifier = '')
 {
     if (!preg_match('#http#', $absolutePath)) {
         if (!file_exists($absolutePath)) {
             throw new \Exception('File not exist! :' . $absolutePath);
         }
     } else {
         //nothing
     }
     if (!$this->owner->primaryKey) {
         throw new \Exception('Owner must have primaryKey when you attach image!');
     }
     $pictureFileName = basename($absolutePath);
     $pictureSubDir = $this->getModule()->getModelSubDir($this->owner);
     $storePath = $this->getModule()->getStorePath($this->owner);
     $newAbsolutePath = $storePath . DIRECTORY_SEPARATOR . $pictureSubDir . DIRECTORY_SEPARATOR . $pictureFileName;
     BaseFileHelper::createDirectory($storePath . DIRECTORY_SEPARATOR . $pictureSubDir, 0775, true);
     copy($absolutePath, $newAbsolutePath);
     unlink($absolutePath);
     if (!file_exists($newAbsolutePath)) {
         throw new \Exception('Cant copy file! ' . $absolutePath . ' to ' . $newAbsolutePath);
     }
     $image = new Image();
     $image->itemId = $this->owner->primaryKey;
     $image->filePath = $pictureSubDir . '/' . $pictureFileName;
     $image->modelName = $this->getModule()->getShortClass($this->owner);
     $image->urlAlias = $this->getAlias($image);
     $image->identifier = $identifier;
     $image->name = substr(yii\helpers\Inflector::slug($pictureFileName), 0, -3);
     // Get the highest position
     // @todo Create function
     $owner = $this->owner;
     $query = (new yii\db\Query())->select('MAX(`position`)')->from(Image::tableName())->where(['modelName' => yii\helpers\StringHelper::basename($owner::className())]);
     $command = $query->createCommand();
     $image->position = $command->queryOne(\PDO::FETCH_COLUMN) + 1;
     if (!$image->save()) {
         return false;
     }
     // Add the translations
     foreach (Yii::$app->params['languages'] as $language => $data) {
         $imageLang = new ImageLang();
         $imageLang->language = $language;
         $image->link('translations', $imageLang);
     }
     if (count($image->getErrors()) > 0) {
         $ar = array_shift($image->getErrors());
         unlink($newAbsolutePath);
         throw new \Exception(array_shift($ar));
     }
     $img = $this->owner->getImage();
     $this->setMainImage($image);
     return $image;
 }

作者:itnel    项目:digitaldali-portal-template-php-yii   
public function upload()
 {
     if ($this->validate()) {
         $image_dir = \Yii::getAlias('@webroot');
         $this->_uploaded_url = implode(DIRECTORY_SEPARATOR, ['', self::DIR_UPLOADS, self::DIR_IMAGES, '']);
         foreach ($this->_segments as $segment) {
             $this->_uploaded_url .= $segment . DIRECTORY_SEPARATOR;
         }
         BaseFileHelper::createDirectory($image_dir . $this->_uploaded_url, 0775, true);
         $this->_uploaded_url .= md5($this->_image_name . time()) . '.' . $this->imageFile->extension;
         $this->imageFile->saveAs($image_dir . $this->_uploaded_url);
         return true;
     } else {
         return false;
     }
 }

作者:barie    项目:yii2-tool   
public static function getAllClasses()
 {
     $result = [];
     foreach (self::getAllAliases() as $alias) {
         $path = \Yii::getAlias($alias);
         $files = is_dir($path) ? BaseFileHelper::findFiles($path) : [$path];
         foreach ($files as $filePath) {
             if (!preg_match('/.*\\/[A-Z]\\w+\\.php/', $filePath)) {
                 continue;
             }
             $className = str_replace([$path, '.php', '/', '@'], [$alias, '', '\\', ''], $filePath);
             $result[] = $className;
         }
     }
     return $result;
 }

作者:scorp7mi    项目:yi   
public function actionFileUploadAvatar()
 {
     if (Yii::$app->request->isPost) {
         $id = Yii::$app->user->id;
         $model = User::findOne($id);
         $path = Yii::getAlias("@frontend/web/images/users/");
         BaseFileHelper::createDirectory($path);
         $model->scenario = 'view';
         $file = UploadedFile::getInstance($model, 'imgsource');
         $name = $file->baseName . '.' . $file->extension;
         $file->saveAs($path . DIRECTORY_SEPARATOR . $name);
         $model->imgsource = $name;
         $model->save();
         return true;
     }
     return false;
 }

作者:scorp7mi    项目:yi   
public static function getImageAdvert($data, $general = true, $original = false)
 {
     $image = [];
     $base = Url::base();
     if ($general) {
         $image[] = $base . '/uploads/adverts/' . $data['idadvert'] . '/general/small_' . $data['general_image'];
     } else {
         $path = \Yii::getAlias("@frontend/web/uploads/adverts/" . $data['idadvert']);
         $files = BaseFileHelper::findFiles($path);
         foreach ($files as $file) {
             if (strstr($file, 'small_') && !strstr($file, 'general')) {
                 $image[] = $base . 'uploads/adverts/' . $data['idadvert'] . '/' . basename($file);
             }
         }
     }
     return $image;
 }

作者:Godscreatur    项目:Book   
/**
  * create book.
  * @return Book|null the saved model or null if saving fails
  */
 public function insert()
 {
     $this->preview = UploadedFile::getInstance($this, 'preview');
     if ($this->validate()) {
         $book = new Book();
         $book->name = $this->name;
         $book->date = strtotime($this->date);
         $book->author_id = $this->author_id;
         if ($book->save()) {
             // если сохранило сообщение, то дописываем файл ------------------------------
             $dir = Yii::getAlias(Yii::$app->params['previewPath']);
             // если надо - создаем каталог
             if (!is_dir($dir)) {
                 BaseFileHelper::createDirectory($dir, 0777);
             }
             $uploaded = false;
             $filename = '';
             if ($this->preview) {
                 $filename = 'b' . $book->book_id . 'preview.' . $this->preview->extension;
                 $uploaded = $this->preview->saveAs($dir . '/' . $filename);
                 // урезаем размер файла, что б не грущили 100500мегабайт и пересохраняем
                 $img = Image::getImagine()->open($dir . '/' . $filename);
                 $size = $img->getSize();
                 $ratio = $size->getWidth() / $size->getHeight();
                 $width = 700;
                 $height = round($width / $ratio);
                 Image::thumbnail($dir . '/' . $filename, $width, $height)->save($dir . '/' . $filename, ['quality' => 80]);
                 // делаем превьюшку
                 $ratio = $size->getWidth() / $size->getHeight();
                 $width = 200;
                 $height = round($width / $ratio);
                 Image::thumbnail($dir . '/' . $filename, $width, $height)->save($dir . '/th_' . $filename, ['quality' => 80]);
             }
             // если файл залился - пишем в базу данные по файлу
             if ($uploaded) {
                 $bookData = Book::findOne($book->book_id);
                 $bookData->preview = $filename;
                 $bookData->save();
             }
             return $book;
         }
     }
     return null;
 }

作者:vechersky    项目:do   
public function actionFileUploadImages()
 {
     if (Yii::$app->request->isPost) {
         $id = Yii::$app->request->post("advert_id");
         $path = Yii::getAlias("@frontend/web/uploads/adverts/" . $id);
         BaseFileHelper::createDirectory($path);
         $file = UploadedFile::getInstanceByName('images');
         $name = time() . '.' . $file->extension;
         $file->saveAs($path . DIRECTORY_SEPARATOR . $name);
         $image = $path . DIRECTORY_SEPARATOR . $name;
         $new_name = $path . DIRECTORY_SEPARATOR . "small_" . $name;
         $size = getimagesize($image);
         $width = $size[0];
         $height = $size[1];
         Image::frame($image, 0, '666', 0)->crop(new Point(0, 0), new Box($width, $height))->resize(new Box(1000, 644))->save($new_name, ['quality' => 100]);
         sleep(1);
         return true;
     }
 }

作者:black-lam    项目:blcms-sho   
public function upload()
 {
     if ($this->validate()) {
         $imagable = \Yii::$app->shop_imagable;
         $dir = $imagable->imagesPath . '/shop-product/';
         if (!empty($this->image)) {
             if (!file_exists($dir)) {
                 BaseFileHelper::createDirectory($dir);
             }
             $newFile = $dir . $this->image->name;
             if ($this->image->saveAs($newFile)) {
                 $image_name = $imagable->create('shop-product', $newFile);
                 unlink($newFile);
                 return $image_name;
             } else {
                 throw new Exception('Image saving failed.');
             }
         }
     }
     return false;
 }

作者:infoweb-internet-solution    项目:yii2-cm   
public function attachFile()
 {
     try {
         $model = $this->owner;
         $model->file = UploadedFile::getInstance($model, 'file');
         if ($model->validate() && $model->file) {
             $fileName = Inflector::slug($model->file->baseName) . '.' . $model->file->extension;
             $folder = $this->getModelSubDir() . '/';
             $model->path = $fileName;
             BaseFileHelper::removeDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}");
             if (!BaseFileHelper::createDirectory(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}")) {
                 throw new Exception(Yii::t('app', 'Failed to create the file upload directory'));
             }
             $model->file->saveAs(Yii::getAlias('@uploadsBasePath') . "/files/{$folder}{$model->path}");
             $model->save();
         }
         return true;
     } catch (yii\base\Exception $e) {
         return $e->getMessage();
     }
 }


问题


面经


文章

微信
公众号

扫码关注公众号