This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]',
'files[n]'..., and you can retrieve them all by passing 'files' as the name.
public static getInstancesByName ( string $name ) : |
||
$name | string | the name of the array of files |
return | the array of UploadedFile objects. Empty array is returned if no adequate upload was found. Please note that this array will contain all files from all sub-arrays regardless how deeply nested they are. |
/** * Action to generate the according folder and file structure from an uploaded zip file. * * @return multitype:multitype: */ public function actionUploadArchive() { if (Setting::Get('disableZipSupport', 'cfiles')) { throw new HttpException(404, Yii::t('CfilesModule.base', 'Archive (zip) support is not enabled.')); } // cleanup all old files $this->cleanup(); Yii::$app->response->format = 'json'; $response = []; foreach (UploadedFile::getInstancesByName('files') as $cFile) { if (strtolower($cFile->extension) === 'zip') { $sourcePath = $this->getZipOutputPath() . DIRECTORY_SEPARATOR . 'zipped.zip'; $extractionPath = $this->getZipOutputPath() . DIRECTORY_SEPARATOR . 'extracted'; if ($cFile->saveAs($sourcePath, false)) { $this->unpackArchive($response, $sourcePath, $extractionPath); $this->generateModelsFromFilesystem($response, $this->getCurrentFolder()->id, $extractionPath); } else { $response['errormessages'][] = Yii::t('CfilesModule.base', 'Archive %filename% could not be extracted.', ['%filename%' => $cFile->name]); } } else { $response['errormessages'][] = Yii::t('CfilesModule.base', '%filename% has invalid extension and was skipped.', ['%filename%' => $cFile->name]); } } $response['files'] = $this->files; return $response; }
/** * Action for file uploading. * @param string $token Widget settings token. * @return void */ public function actionUpload($token) { $settings = $this->getSettings($token); $files = UploadedFile::getInstancesByName($settings['name']); $errorMaxSize = []; $errorFormat = []; $errorOther = []; $items = []; $names = []; UploadImageHelper::$uploadPath = $settings['uploadPath']; foreach ($files as $file) { if (!$this->validateFileSize($file, $settings['maxFileSize'])) { $errorMaxSize[] = $file->name; continue; } if (!in_array($file->type, ['image/gif', 'image/jpeg', 'image/png'])) { $errorFormat[] = $file->name; continue; } if ($file->error != UPLOAD_ERR_OK) { $errorOther[] = $file->name; continue; } $items[] = $this->upload($settings, $file); $names[] = $file->name; } $response = Yii::$app->getResponse(); $response->format = \yii\web\Response::FORMAT_RAW; $response->getHeaders()->add('Content-Type', 'text/plain'); return Json::encode(['items' => $items, 'names' => $names, 'errorMaxSize' => $errorMaxSize, 'errorFormat' => $errorFormat, 'errorOther' => $errorOther]); }
public function actionUpload() { Yii::$app->response->format = Response::FORMAT_JSON; if (!Yii::$app->request->isAjax) { throw new BadRequestHttpException(); } $files = UploadedFile::getInstancesByName('files'); $baseDir = Yii::getAlias(Module::getInstance()->basePath); if (!is_dir($baseDir)) { mkdir($baseDir); } $dir = $baseDir . DIRECTORY_SEPARATOR . $_POST['galleryId']; if (!is_dir($dir)) { mkdir($dir); } $response = []; foreach ($files as $key => $file) { if (Module::getInstance()->uniqueName) { $name = $this->getUniqueName($file); } else { $name = $file->name; } $file->saveAs($dir . DIRECTORY_SEPARATOR . $name); $model = new GalleryFile(); $model->galleryId = $_POST['galleryId']; $model->file = $name; if ($model->save()) { $response = ['status' => true, 'message' => 'Success', 'html' => $this->renderAjax('_image', ['model' => $model])]; } break; } return $response; }
/** * Загрузка файлов по имени. Возвращает массив путей к загруженным файлам, относительно DOCUMENT_ROOT. * @param $name имя файла * @return array */ public function uploadFiles($name) { $this->checkModelFolder(); // Множественная загрузка файлов $files = UploadedFile::getInstancesByName($name); // Единичная загрузка. Удаляем старые файлы if (empty($files) and $file = UploadedFile::getInstanceByName($name)) { $this->deleteFiles(); $files = array($file); } $fileNames = []; if (!empty($files)) { foreach ($files as $file) { $fileName = FileHelper::getNameForSave($this->getSavePath(), $file->name); $fileNames[] = $this->getRelPath() . $fileName; $savePath = $this->getSavePath() . $fileName; $file->saveAs($savePath); chmod($savePath, $this->filePerm); if (FileHelper::isImage($savePath)) { Yii::$app->resizer->resizeIfGreater($savePath, $this->maxWidth, $this->maxHeight); } } } return $fileNames; }
/** * Upload file * * @access public * @param $attr * @param $name * @param $ext * @param $path * @param array $allowed list of allowed file types * @return boolean * @throws \yii\base\ErrorException */ public function upload($attr, $name, $ext, $path, array $allowed = []) { $this->uploadErrors = []; $allowed = array_filter($allowed); $attr = str_replace('[]', '', $attr); $files = UploadedFile::getInstancesByName($attr); $uploaded = []; if (!$files) { $this->uploadErrors[] = Yii::t('app', 'Select at least one file'); return false; } $filesCount = sizeof($files); foreach ($files as $file) { if ($filesCount > 1) { $name = Yii::$app->getSecurity()->generateRandomString(); } if ($file->getHasError()) { $this->uploadErrors[] = Yii::t('app', static::$errors[$file->error]); continue; } if (!in_array($file->type, static::$mimeTypes)) { $this->uploadErrors[] = Yii::t('app', '{file} has invalid file type', ['file' => $file->baseName]); continue; } if ($allowed && !in_array($file->extension, $allowed)) { $this->uploadErrors[] = Yii::t('app', '{file} has invalid file type', ['file' => $file->baseName]); continue; } FileHelper::createDirectory($path); if ($file->saveAs($path . '/' . $name . '.' . $ext)) { $uploaded[] = ['path' => $path, 'name' => $name, 'ext' => $ext]; } } return $uploaded; }
/** * Action to upload multiple files. * @return multitype:boolean multitype: */ public function actionIndex() { Yii::$app->response->format = 'json'; if (!$this->canWrite()) { throw new HttpException(401, Yii::t('CfilesModule.base', 'Insufficient rights to execute this action.')); } $response = []; foreach (UploadedFile::getInstancesByName('files') as $cFile) { $folder = $this->getCurrentFolder(); $currentFolderId = empty($folder) ? self::ROOT_ID : $folder->id; // check if the file already exists in this dir $filesQuery = File::find()->contentContainer($this->contentContainer)->joinWith('baseFile')->readable()->andWhere(['title' => File::sanitizeFilename($cFile->name), 'parent_folder_id' => $currentFolderId]); $file = $filesQuery->one(); // if not, initialize new File if (empty($file)) { $file = new File(); $humhubFile = new \humhub\modules\file\models\File(); } else { $humhubFile = $file->baseFile; // logging file replacement $response['infomessages'][] = Yii::t('CfilesModule.base', '%title% was replaced by a newer version.', ['%title%' => $file->title]); $response['log'] = true; } $humhubFile->setUploadedFile($cFile); if ($humhubFile->validate()) { $file->content->container = $this->contentContainer; $folder = $this->getCurrentFolder(); if ($folder !== null) { $file->parent_folder_id = $folder->id; } if ($file->save()) { $humhubFile->object_model = $file->className(); $humhubFile->object_id = $file->id; $humhubFile->save(); $this->files[] = array_merge($humhubFile->getInfoArray(), ['fileList' => $this->renderFileList()]); } else { $count = 0; $messages = ""; // show multiple occurred errors foreach ($file->errors as $key => $message) { $messages .= ($count++ ? ' | ' : '') . $message[0]; } $response['errormessages'][] = Yii::t('CfilesModule.base', 'Could not save file %title%. ', ['%title%' => $file->title]) . $messages; $response['log'] = true; } } else { $count = 0; $messages = ""; // show multiple occurred errors foreach ($humhubFile->errors as $key => $message) { $messages .= ($count++ ? ' | ' : '') . $message[0]; } $response['errormessages'][] = Yii::t('CfilesModule.base', 'Could not save file %title%. ', ['%title%' => $humhubFile->filename]) . $messages; $response['log'] = true; } } $response['files'] = $this->files; return $response; }
private static function prepareUpload($para) { if (isset($_FILES[$para])) { if (is_array($_FILES[$para]['name'])) { $attaches = UploadedFile::getInstancesByName($para); } else { $attach = UploadedFile::getInstanceByName($para); if (!empty($attach)) { $attaches = [$attach]; } else { return ['status' => false, 'msg' => self::multiLang(EC_UPLOAD_PREPARE_ERROR_NO_FILE_UPLOAD)]; } } if (!empty($attaches)) { if (self::$_allowPartUpload) { $feedback = []; $file = []; $msg = []; foreach ($attaches as $v) { $check = self::prepareCheck($v); if ($check['status']) { $file[] = $v; } else { $msg[] = $check['msg']; } } $feedback['status'] = false; if (!empty($file)) { $feedback['file'] = $file; $feedback['status'] = true; } if (!empty($msg)) { $feedback['msg'] = $msg; } return $feedback; } else { $checkall = true; $msg = []; foreach ($attaches as $v) { $check = self::prepareCheck($v); if (!$check['status']) { $checkall = false; } $msg[] = $check['msg']; } if ($checkall) { return ['status' => true, 'file' => $attaches]; } else { return ['status' => false, 'msg' => $msg]; } } } else { return ['status' => false, 'msg' => self::multiLang(EC_UPLOAD_PREPARE_ERROR_NO_FILE_UPLOAD)]; } } else { return ['status' => false, 'msg' => self::multiLang(EC_UPLOAD_PREPARE_ERROR_NO_FILE_NAMED) . '(' . $para . ')']; } }
/** * @inheritdoc */ public function load($data, $formName = null) { $files = \yii\web\UploadedFile::getInstancesByName('logo'); if (count($files) != 0) { $file = $files[0]; $this->logo = $file; } return parent::load($data, $formName); }
public function actionUpload() { $file = UploadedFile::getInstancesByName('file')[0]; if ($file->saveAs($this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $file->name)) { return json_encode(['uploadedFile' => $file->name]); } else { throw new \Exception(\Yii::t('yii', 'File upload failed.')); } }
/** * Action upload anh */ public function actionAdditemimage() { // Cac thong so mac dinh cua image // Kieu upload $type = Yii::$app->request->post('type'); // Module upload $module = Yii::$app->request->post('module'); // Cac truong cua image $columns = \yii\helpers\Json::decode(Yii::$app->request->post('columns')); // danh sach cac anh duoc upload $gallery = []; // Id cua gallery $id = uniqid('g_'); // Begin upload image if ($type == Gallery::TYPE_UPLOAD) { // Upload anh khi chon type la upload $images = \yii\web\UploadedFile::getInstancesByName('image'); if (empty($images)) { return; } foreach ($images as $image) { // Tao lai id khi upload nhieu anh $id = uniqid('g_'); $ext = FileHelper::getExtention($image); if (!empty($ext)) { $fileDir = strtolower($module) . '/' . date('Y/m/d/'); $fileName = uniqid() . '.' . $ext; $folder = Yii::getAlias(Yii::$app->getModule('gallery')->syaDirPath) . Yii::$app->getModule('gallery')->syaDirUpload . '/' . $fileDir; FileHelper::createDirectory($folder); $image->saveAs($folder . $fileName); $gallery[$id] = ['url' => $fileDir . $fileName, 'type' => $type]; } } } elseif ($type == Gallery::TYPE_URL) { // Lay ra duong dan anh khi type la url $image = Yii::$app->request->post('image'); if (empty($image)) { return; } $gallery[$id] = ['url' => $image, 'type' => $type]; } elseif ($type == Gallery::TYPE_PATH) { $image = Yii::$app->request->post('image'); if (empty($image)) { return; } $images = explode(',', $image); if (!empty($image) && is_array($images)) { foreach ($images as $img) { $id = uniqid('g_'); $gallery[$id] = ['url' => $img, 'type' => $type]; } } } // End upload image echo \sya\gallery\models\Gallery::generateGalleryTemplate($gallery, $module, $columns); }
public function actionUpload($id) { $picture = new UploadForm(); //$picture->tour_id = $id; $picture->image = UploadedFile::getInstancesByName('attachment_' . $id . ''); //echo '<pre> File2: ' . print_r( $picture->image, TRUE). '</pre>'; die(); $picture->id = $id; $picture->saveImages(); return $this->redirect(Yii::$app->request->referrer); }
public function run() { $ds = DIRECTORY_SEPARATOR; $basePath = Yii::getAlias('@upload'); //仅删除图片操作 if (Yii::$app->getRequest()->get('action', '') == 'del') { $path = Yii::$app->getRequest()->get('path'); $field = Yii::$app->getRequest()->get('field'); $dir = Yii::$app->getRequest()->get('dir'); $filePath = $basePath . $ds . $path; if (is_file($filePath)) { @unlink($filePath); } //只是尝试删除文件 $data = ['action' => 'del', 'field' => $field, 'path' => $path, 'dir' => $dir]; $this->addRecord($data); //删除一条旧记录 // fb($filePath); echo Json::encode([]); Yii::$app->end(); } //上传图片 if (Yii::$app->getRequest()->isPost) { $name = Yii::$app->getRequest()->post('name'); $field = Yii::$app->getRequest()->post('field'); $dir = Yii::$app->getRequest()->post('dir'); $files = UploadedFile::getInstancesByName($name); $route = Yii::$app->getRequest()->post('route'); $path = $basePath . $ds . $dir . $ds . date('Y-m'); if (!is_dir($path) && !FileHelper::createDirectory($path)) { //创建不存在的目录 //创建失败,权限问题 } //存储 $initialPreview = []; $initialPreviewConfig = []; foreach ($files as $file) { $newName = $this->getNameRule($file->baseName, $file->extension, $path); $filePath = $path . $ds . $newName . '.' . $file->extension; $file->saveAs($filePath); //生成新的文件名 $key = $newName . '.' . $file->extension; //文件名 $src = Yii::getAlias('@web') . '/' . 'upload' . '/' . $dir . '/' . date('Y-m') . '/' . $key; $url = Url::to([$route, 'action' => 'del', 'dir' => $dir, 'field' => $field, 'path' => $dir . '/' . date('Y-m') . '/' . $key]); //删除按钮地址 $initialPreview[] = Html::img($src, ['class' => 'file-preview-image', 'style' => 'height:160px;max-width:625px']); $initialPreviewConfig[] = ['caption' => "{$key}", 'width' => '120px', 'url' => $url, 'key' => $key]; $data = ['action' => 'ins', 'field' => $field, 'path' => $dir . '/' . date('Y-m') . '/' . $key, 'dir' => $dir]; $this->addRecord($data); //插入一条新记录 } echo Json::encode(['initialPreview' => $initialPreview, 'initialPreviewConfig' => $initialPreviewConfig, 'append' => true]); } }
/** * Runs the action. */ public function run() { Yii::$app->response->format = Response::FORMAT_JSON; $inputName = Yii::$app->request->get('inputName'); $uploadedFile = UploadedFile::getInstancesByName($inputName)[0]; if ($uploadedFile instanceof UploadedFile) { $uploadedFile->saveAs($this->getFullPath($uploadedFile)); return ['files' => [['name' => $this->getFullName($uploadedFile), 'size' => $uploadedFile->size, 'url' => $this->getFullUrl($uploadedFile), 'relativeUrl' => $this->getRelativeUrl($uploadedFile)]]]; } return []; }
public function saveEssay() { $essay = new Essays(); $essay->text = htmlentities($this->text, ENT_NOQUOTES); $essay->user_id = Yii::$app->user->id; $essay->create_date = date("Y-m-d H:i:s"); $photo = UploadedFile::getInstancesByName('photo'); if (isset($photo[0]) && $photo[0]->tempName) { $photo_name = uniqid() . '.' . $photo[0]->getExtension(); $essay->photo_path = $photo_name; if ($essay->validate()) { $photo[0]->saveAs(Essays::ESSAY_PHOTO_PATH . $photo_name); } } return $essay->save(); }
/** * Before validate event. */ public function beforeValidate() { $this->normalizeAttributes(); foreach ($this->attributes as $attribute => $storageConfig) { $this->_files[$attribute] = $storageConfig->multiple ? UploadedFile::getInstances($this->owner, $attribute) : UploadedFile::getInstance($this->owner, $attribute); if (empty($this->_files[$attribute])) { $this->_files[$attribute] = $storageConfig->multiple ? UploadedFile::getInstancesByName($attribute) : UploadedFile::getInstanceByName($attribute); } if ($this->_files[$attribute] instanceof UploadedFile) { $this->owner->{$attribute} = $this->_files[$attribute]; } elseif (is_array($this->_files[$attribute]) && !empty($this->_files[$attribute])) { $this->owner->{$attribute} = array_filter((array) $this->_files[$attribute], function ($file) { return $file instanceof UploadedFile; }); } } }
public function run() { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $root = $this->folder === null ? Yii::getAlias('@webroot/images') : $this->folder; if (!is_dir($root)) { mkdir($root, 0700, true); } $webroot = $this->webroot === null ? Yii::getAlias('@webroot') : $this->webroot; $relpath = Yii::$app->request->post('path', ''); $this->path = $root; if (realpath($root . $relpath) && strpos(realpath($root . $relpath), $root) !== false) { $this->path = realpath($root . $relpath) . DIRECTORY_SEPARATOR; } $folder = str_replace($webroot, '', $this->path); $result = (object) ['error' => 0, 'msg' => '', 'files' => [], 'path' => '', 'baseurl' => '']; $msg = []; if (true || Yii::$app->request->isPost) { if ($this->uploadModel === null) { $uploadModel = \yii\base\DynamicModel::validateData(['images' => UploadedFile::getInstancesByName('files')], [[['images'], 'file', 'extensions' => 'jpg, png, jpeg', 'maxFiles' => 10, 'mimeTypes' => 'image/jpeg, image/png']]); } else { $uploadModel = $this->uploadModel; $uploadModel->images = UploadedFile::getInstancesByName('files'); $uploadModel->validate(); } if (!$uploadModel->hasErrors() && count($uploadModel->images)) { foreach ($uploadModel->images as $image) { $uploadedFile = $this->saveImage($image); if ($uploadedFile === false) { $result->error = 4; } else { $result->files[] = $folder . $uploadedFile; $this->afterFileSave($uploadedFile, $this->path, $folder); } } } else { $result->error = 3; } } else { $result->error = 2; } $result->msg = $this->messages[$result->error]; // \yii\helpers\VarDumper::dump($_FILES['files']); // \yii\helpers\VarDumper::dump($uploadModel); return $result; }
public function save($runValidation = true, $attributes = NULL) { $class = get_class($this); if ($class == 'Accounts') { if (Accounts::findOne($this->id)) { $this->isNewRecord = false; } } $a = parent::save($runValidation, $attributes); if ($a) { //if (isset($_POST['Files'])) { //$this->attributes = $_POST['Files']; $tmps = \yii\web\UploadedFile::getInstancesByName('Files'); // proceed if the images have been set if (isset($tmps) && count($tmps) > 0) { \Yii::info('saved'); // go through each uploaded image $configPath = \app\helpers\Linet3Helper::getSetting("company.path"); foreach ($tmps as $image => $pic) { $img_add = new Files(); $img_add->name = $pic->name; //it might be $img_add->name for you, filename is just what I chose to call it in my model $img_add->path = "files/"; $img_add->parent_type = get_class($this); $img_add->parent_id = $this->id; // this links your picture model to the main model (like your user, or profile model) $img_add->save(); // DONE if ($pic->saveAs($img_add->getFullFilePath())) { // add it to the main model now } else { echo 'Cannot upload!'; } } if (isset($_FILES)) { Yii::info(print_r($_FILES, true)); unset($_FILES); $tmps = \yii\web\UploadedFile::reset(); } //} } } //endFile return $a; }
public function actionAddCategory() { $user = Yii::$app->user->identity; if ($user->role == User::ROLE_ADMIN) { $model = new Category(); $image = new Image(); $model->load(Yii::$app->request->post(), ''); $image->img = UploadedFile::getInstancesByName("image"); if ($image->validate() && $model->save()) { if (!empty($image->img)) { $image->uploads($model, Image::CATEGORY_STATUS); } return $model; } return array_merge($model->getErrors(), $image->getErrors()); } return "Access denied"; }
public function actionAddBlog() { $model = new Blog(); $image = new Image(); $data = Yii::$app->request->post(); $model->load($data, ''); $image->img = UploadedFile::getInstancesByName("image"); if ($image->validate() && $model->save()) { if (!empty($model->categorys)) { $model->setCategories(); } if (!empty($image->img)) { $image->uploads($model, Image::BLOG_STATUS); } return $model; } return array_merge($model->getErrors(), $image->getErrors()); }
public function saveUploads($event) { $files = UploadedFile::getInstancesByName('file'); if (!empty($files)) { foreach ($files as $file) { if (!$file->saveAs($this->getModule()->getUserDirPath() . DIRECTORY_SEPARATOR . $file->name)) { throw new \Exception(\Yii::t('yii', 'File upload failed.')); } } } $userTempDir = $this->getModule()->getUserDirPath(); foreach (FileHelper::findFiles($userTempDir) as $file) { if (!$this->getModule()->attachFile($file, $this->owner)) { throw new \Exception(\Yii::t('yii', 'File upload failed.')); } } rmdir($userTempDir); }
public function actionCreate() { $files = UploadedFile::getInstancesByName('image'); $className = Yii::$app->request->post('class'); if (sizeof($files) > 0 && $className) { $ret = ''; foreach ($files as $fileInstance) { if (array_search($fileInstance->type, Image::getAllowed()) === false) { continue; } $fileName = md5(time() . $fileInstance->tempName) . "." . $fileInstance->extension; $path = Yii::getAlias('@webroot') . DIRECTORY_SEPARATOR . Image::IMAGEFIELD_DIR . DIRECTORY_SEPARATOR . $fileName; $fileInstance->saveAs($path); $simpleImage = new SimpleImage(); $simpleImage->load($path); if ($simpleImage->getWidth() > 1920 || $simpleImage->getHeight() > 1080) { $simpleImage->resizeToWidth(1920); $simpleImage->save($path); } $image = new Image(); $image->file = $fileName; $image->class = $className; $tmp = explode('\\', $className); if (Yii::$app->request->post('field')) { $image->field = Yii::$app->request->post('field'); } if ($image->save()) { if (Yii::$app->request->post('json')) { return json_encode(['id' => $image->id, 'src' => $image->path]); } else { if (Yii::$app->request->post('field')) { $ret .= Yii::$app->view->renderFile('@vendor/floor12/yii2-imagefield/views/_singleForm.php', ['field' => $image->field, 'image' => $image, 'class' => $tmp[2], 'hidden' => 0]); } else { $ret .= Yii::$app->view->renderFile('@vendor/floor12/yii2-imagefield/views/_form.php', ['image' => $image, 'class' => $className, 'hidden' => 1]); } } } } echo $ret; } else { throw new BadRequestHttpException(); } }
/** * Action which handles file uploads * * The result is an json array of all uploaded files. */ public function actionUpload() { Yii::$app->response->format = 'json'; // Object which the uploaded file(s) belongs to (optional) $object = null; $objectModel = Yii::$app->request->get('objectModel'); $objectId = Yii::$app->request->get('objectId'); if ($objectModel != "" && $objectId != "" && \humhub\libs\Helpers::CheckClassType($objectModel, \yii\db\ActiveRecord::className())) { $givenObject = $objectModel::findOne(['id' => $objectId]); // Check if given object is HActiveRecordContent or HActiveRecordContentAddon and can be written by the current user if ($givenObject !== null && ($givenObject instanceof ContentActiveRecord || $givenObject instanceof ContentAddonActiveRecord) && $givenObject->content->canWrite()) { $object = $givenObject; } } $files = array(); foreach (UploadedFile::getInstancesByName('files') as $cFile) { $files[] = $this->handleFileUpload($cFile, $object); } return ['files' => $files]; }
public function uploadFiles($attribute, $subfolder = '') { $savePath = array(); $model = new UploadForm('image', true); $model->file = UploadedFile::getInstancesByName($attribute); if ($model->file) { if ($model->validate()) { foreach ($model->file as $file) { // get the new name of file $newFileName = $file->baseName . '_' . time() . '.' . $file->extension; $file->saveAs(Yii::$app->params['uploadPath'] . $subfolder . '/' . $newFileName); $returnPath = $subfolder . '/' . $newFileName; $savePath[] = $returnPath; // create a thumbnail $thumbPath = $subfolder . '/thumb/thumb-' . $newFileName; Image::thumbnail(Yii::$app->params['uploadPath'] . $returnPath, $this->thumbWidth, $this->thumbHeight)->save(Yii::$app->params['uploadPath'] . $thumbPath, ['quality' => 80]); } } } return $savePath; }
public function actionIndex() { if (\Yii::$app->request->isPost) { $uploaded = UploadedFile::getInstancesByName('cmlFile'); $files = []; $date = time(); $dir = \Yii::getAlias(\Yii::$app->getModule('data')->importDirPath . '/'); if (!empty($uploaded)) { foreach ($uploaded as $k => $file) { if ($file->saveAs($dir . "cml{$date}_{$k}.xml")) { $files[] = $dir . "cml{$date}_{$k}.xml"; } } if (!empty($files)) { $params = ['files' => $files]; BackgroundTasks::addTask(['name' => 'CommerceML import', 'description' => 'CommerceML import', 'action' => 'data/commerceml/import', 'params' => Json::encode($params), 'init_event' => 'import'], ['create_notification' => true]); } } } return $this->render('index'); }
public function run() { $response = []; $uploadedFiles = UploadedFile::getInstancesByName($this->fileParam); foreach ($uploadedFiles as $uploadedFile) { $responseFile = new \stdClass(); $responseFile->{$this->responseParamsMap['name']} = $uploadedFile->name; $responseFile->{$this->responseParamsMap['type']} = $uploadedFile->type; $responseFile->{$this->responseParamsMap['size']} = $uploadedFile->size; if (!$uploadedFile->hasError) { $model = DynamicModel::validateData(['file' => $uploadedFile], $this->validationRules); if (!$model->hasErrors()) { $filesystemComponent = $this->getFilesystemComponent(); $filesystem = $this->getFilesystem(); /** @var FileInterface $fileClass */ $fileClass = $this->fileClass; $file = $fileClass::getInstanceFromUploadedFile($uploadedFile); //$path = $this->path . DIRECTORY_SEPARATOR . $uploadedFile->name; $path = $this->path . DIRECTORY_SEPARATOR . date('dmYHis') . '-' . $file->getBasename() . '.' . $uploadedFile->extension; $path = $filesystemComponent->saveFile($file, $filesystem, $path); if ($path) { $file->setPath($path); $responseFile->{$this->responseParamsMap['filesystem']} = $filesystem; $responseFile->{$this->responseParamsMap['path']} = $path; $responseFile->{$this->responseParamsMap['name']} = $uploadedFile->name; $responseFile->{$this->responseParamsMap['url']} = $filesystemComponent->getUrl($file, $filesystem); $responseFile->{$this->responseParamsMap['deleteUrl']} = Url::to([$this->deleteRoute, 'path' => $path]); } else { $responseFile->{$this->responseParamsMap['error']} = 'Saving error'; } } else { $responseFile->{$this->responseParamsMap['error']} = $model->errors; } } else { $responseFile->{$this->responseParamsMap['error']} = $uploadedFile->error; } $response['files'][] = $responseFile; } return $this->multiple ? $response : array_shift($response); }
/** * Handle the banner image upload */ public function actionBannerUpload() { \Yii::$app->response->format = 'json'; $model = new \humhub\models\forms\UploadProfileImage(); $json = array(); $files = \yii\web\UploadedFile::getInstancesByName('bannerfiles'); $file = $files[0]; $model->image = $file; if ($model->validate()) { $profileImage = new \humhub\libs\ProfileBannerImage($this->getSpace()->guid); $profileImage->setNew($model->image); $json['error'] = false; $json['name'] = ""; $json['url'] = $profileImage->getUrl(); $json['size'] = $model->image->size; $json['deleteUrl'] = ""; $json['deleteType'] = ""; } else { $json['error'] = true; $json['errors'] = $model->getErrors(); } return ['files' => $json]; }
/** * Action to generate the according folder and file structure from an uploaded zip file. * @return multitype:multitype: */ public function actionUploadZippedFolder() { // cleanup all old files $this->cleanup(); Yii::$app->response->format = 'json'; $response = []; foreach (UploadedFile::getInstancesByName('files') as $cFile) { if (strtolower($cFile->extension) === 'zip') { $sourcePath = $this->getZipOutputPath() . DIRECTORY_SEPARATOR . 'zipped.zip'; $extractionPath = $this->getZipOutputPath() . DIRECTORY_SEPARATOR . 'extracted'; if ($cFile->saveAs($sourcePath, false)) { $this->zipToFolder($response, $sourcePath, $extractionPath); $this->folderToModels($response, $this->getCurrentFolder()->id, $extractionPath); } else { $response['errormessages'][] = Yii::t('CfilesModule.base', 'Archive %filename% could not be extracted.', ['%filename%' => $cFile->name]); } } else { $response['errormessages'][] = Yii::t('CfilesModule.base', '%filename% has invalid extension and was skipped.', ['%filename%' => $cFile->name]); } } $response['files'] = $this->files; return $response; }
protected function upload($name) { $files = UploadedFile::getInstancesByName($name); $root = Yii::getAlias(Yii::$app->params['upload_dir']); if (!is_dir($root)) { mkdir($root, 0755); } $folder = date('Y-m-d') . '/'; if (!is_dir($root . $folder)) { mkdir($root . $folder, 0755); } $paths = array(); foreach ($files as $file) { $ext = $file->getExtension(); if (!in_array(strtolower($ext), array('jpg', 'gif', 'png'))) { continue; } $filename = time() . '_' . rand(0, PHP_INT_MAX) . '.' . $ext; $image = Yii::$app->image->load($file->tempName); $image->resize(1000)->save($root . $folder . $filename, 30); $paths[] = $folder . $filename; } return $paths; }
/** * E-Mail Mailing Settings */ public function actionDesign() { $form = new \humhub\modules\admin\models\forms\DesignSettingsForm(); #$assetPrefix = Yii::$app->assetManager->publish(dirname(__FILE__) . '/../resources', true, 0, defined('YII_DEBUG')); #Yii::$app->clientScript->registerScriptFile($assetPrefix . '/uploadLogo.js'); if ($form->load(Yii::$app->request->post())) { $files = \yii\web\UploadedFile::getInstancesByName('logo'); if (count($files) != 0) { $file = $files[0]; $form->logo = $file; } if ($form->validate()) { Setting::Set('theme', $form->theme); Setting::Set('paginationSize', $form->paginationSize); Setting::Set('displayNameFormat', $form->displayName); Setting::Set('spaceOrder', $form->spaceOrder, 'space'); if ($form->logo) { $logoImage = new \humhub\libs\LogoImage(); $logoImage->setNew($form->logo); } // read and save colors from current theme \humhub\components\Theme::setColorVariables($form->theme); Yii::$app->getSession()->setFlash('data-saved', Yii::t('AdminModule.controllers_SettingController', 'Saved')); Yii::$app->response->redirect(Url::toRoute('/admin/setting/design')); } } else { $form->theme = Setting::Get('theme'); $form->paginationSize = Setting::Get('paginationSize'); $form->displayName = Setting::Get('displayNameFormat'); $form->spaceOrder = Setting::Get('spaceOrder', 'space'); } $themes = \humhub\components\Theme::getThemes(); return $this->render('design', array('model' => $form, 'themes' => $themes, 'logo' => new \humhub\libs\LogoImage())); }
/** * Action upload anh */ public function actionAdditemimage() { // Cac thong so mac dinh cua image // Kieu upload $type = Yii::$app->request->post('type'); // Module upload $module = Yii::$app->request->post('module'); // Attribute name $attribute = Yii::$app->request->post('attribute'); // Cac truong cua image $columns = Json::decode(Yii::$app->request->post('columns')); $templateInfomationImage = Yii::$app->request->post('templateInfomationImage'); $templateInfomationImageDetail = Yii::$app->request->post('templateInfomationImageDetail'); // danh sach cac anh duoc upload $gallery = []; // Column defalt image $columnsDefault = ['title' => '', 'caption' => '', 'alt_text' => '']; // Id cua gallery $id = uniqid('g_'); // Begin upload image if ($type == Gallery::TYPE_UPLOAD) { // Upload anh khi chon type la upload $images = UploadedFile::getInstancesByName('image'); if (empty($images)) { return; } foreach ($images as $image) { // Tao lai id khi upload nhieu anh $id = uniqid('g_'); $ext = FileHelper::getExtention($image); if (!empty($ext)) { $fileDir = strtolower($module) . '/' . date('Y/m/d/'); $fileName = pathinfo($image, PATHINFO_BASENAME); $folder = Yii::getAlias(Yii::$app->getModule('gallery')->syaDirPath) . Yii::$app->getModule('gallery')->syaDirUpload . '/' . $fileDir; FileHelper::createDirectory($folder); $image->saveAs($folder . $fileName); $columnsDefault['title'] = reset(explode('.', $fileName)); $gallery[$id] = ArrayHelper::merge(['url' => $fileDir . $fileName, 'type' => $type], $columnsDefault); } } $template = Gallery::generateGalleryTemplateByPath($gallery); } elseif ($type == Gallery::TYPE_URL) { // Lay ra duong dan anh khi type la url $image = Yii::$app->request->post('image'); $columnsDefault = Json::decode($image); if (empty($image)) { return; } $gallery[$id] = ArrayHelper::merge(['type' => $type], $columnsDefault); $template = Gallery::generateGalleryTemplate($gallery, $columns, $module, $attribute, $templateInfomationImage, $templateInfomationImageDetail); } elseif ($type == Gallery::TYPE_PATH) { $image = Yii::$app->request->post('image'); if (empty($image)) { return; } $images = explode(';', $image); if (!empty($image) && is_array($images)) { foreach ($images as $img) { $columnsDefault = Json::decode($img); $id = uniqid('g_'); $gallery[$id] = ArrayHelper::merge(['type' => $type], $columnsDefault); } } $template = Gallery::generateGalleryTemplate($gallery, $columns, $module, $attribute, $templateInfomationImage, $templateInfomationImageDetail); } // End upload image echo $template; }