getInstanceByName() публичный статический метод

The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').
public static getInstanceByName ( string $name ) : null | UploadedFile
$name string the name of the file input field.
Результат null | UploadedFile the instance of the uploaded file. Null is returned if no file is uploaded for the specified name.
 /**
  * @inheritdoc
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         $file = UploadedFile::getInstanceByName($this->uploadParam);
         $model = new DynamicModel(compact($this->uploadParam));
         $model->addRule($this->uploadParam, 'file', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('upload', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'checkExtensionByMimeType' => false, 'wrongExtension' => Yii::t('upload', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate();
         if ($model->hasErrors()) {
             $result = ['error' => $model->getFirstError($this->uploadParam)];
         } else {
             $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension;
             $request = Yii::$app->request;
             $image_name = $this->temp_path . $model->{$this->uploadParam}->name;
             $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($this->width, $this->height))->save($image_name);
             // watermark
             if ($this->watermark != '') {
                 $image = Image::watermark($image_name, $this->watermark)->save($image_name);
             }
             if ($image->save($image_name)) {
                 // create Thumbnail
                 if ($this->thumbnail && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) {
                     Image::thumbnail($this->temp_path . $model->{$this->uploadParam}->name, $this->thumbnail_width, $this->thumbnail_height)->save($this->temp_path . '/thumbs/' . $model->{$this->uploadParam}->name);
                 }
                 $result = ['filelink' => $model->{$this->uploadParam}->name];
             } else {
                 $result = ['error' => Yii::t('upload', 'ERROR_CAN_NOT_UPLOAD_FILE')];
             }
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         return $result;
     } else {
         throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST'));
     }
 }
Пример #2
2
 /**
  * @inheritdoc
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         $post = Yii::$app->request->post();
         if (!empty($post['method'])) {
             $file = basename($post['file']);
             if (file_exists($this->getPath() . $file)) {
                 unlink($this->getPath() . $file);
             }
         } else {
             $image = \yii\web\UploadedFile::getInstanceByName('upload');
             if (!empty($image)) {
                 $imageFileType = strtolower(pathinfo($image->name, PATHINFO_EXTENSION));
                 $allowed = ['png', 'jpg', 'gif', 'jpeg'];
                 if (!empty($image) and in_array($imageFileType, $allowed)) {
                     $fileName = $this->getFileName($image);
                     $image->saveAs($this->getPath() . $fileName);
                     $imagine = Image::getImagine();
                     $photo = $imagine->open($this->getPath() . $fileName);
                     $photo->thumbnail(new Box($this->maxWidth, $this->maxHeight))->save($this->getPath() . $fileName, ['quality' => 90]);
                 }
             }
         }
     }
     $data['url'] = $this->getUrl();
     $data['path'] = $this->getPath();
     $data['ext'] = $this->getFileExt();
     BrowseAssets::register($this->controller->view);
     $this->controller->layout = '@vendor/bajadev/yii2-ckeditor/views/layout/image';
     return $this->controller->render('@vendor/bajadev/yii2-ckeditor/views/browse', ['data' => $data]);
 }
Пример #3
0
 /**
  * Upload a file via ajax.
  * @return string JSON string will return with uploaded file information or if upload failed an error message.
  */
 public function actionUpload()
 {
     $model = new Media();
     $model->scenario = Media::SCENARIO_UPLOAD;
     $request = Yii::$app->getRequest();
     try {
         $model->mediaFile = UploadedFile::getInstanceByName('mediaUploadFile');
         $model->load($request->post());
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
         if ($model->upload()) {
             $items['baseUrl'] = Yii::getAlias('@web');
             $items['files'] = [['id' => $model->id, 'name' => $model->name, 'size' => $model->size, 'url' => $model->url, 'thumbnailUrl' => $model->isImage ? Yii::$app->image->thumb($model->url, $model->thumbStyle) : null, 'deleteUrl' => Url::to(['/media/upload/delete', 'id' => $model->id]), 'deleteType' => 'POST', 'status' => $model->status, 'type' => $model->type]];
         } else {
             if ($model->hasErrors()) {
                 $errorMessage = '';
                 foreach ($model->getFirstErrors() as $error) {
                     $errorMessage .= "{$error}\n";
                 }
                 $items['files'] = [['error' => $errorMessage]];
             }
         }
     } catch (\Exception $e) {
         $items['files'] = [['error' => $e->getMessage()]];
     }
     return $items;
 }
 public function actionData($file = false)
 {
     \Yii::$app->response->format = Response::FORMAT_JSON;
     if (\Yii::$app->request->isPost) {
         /**@var Module $module */
         $module = Module::getInstance();
         $model = new DynamicModel(['file' => null]);
         $model->addRule('file', 'file', ['extensions' => $module->expansions, 'maxSize' => $module->maxSize]);
         $model->file = UploadedFile::getInstanceByName('image');
         if ($model->validate()) {
             if (!is_dir(\Yii::getAlias($module->uploadDir))) {
                 FileHelper::createDirectory(\Yii::getAlias($module->uploadDir));
             }
             $oldFileName = $model->file->name;
             $newFileName = $module->isFileNameUnique ? uniqid() . '.' . $model->file->extension : $oldFileName;
             $newFullFileName = \Yii::getAlias($module->uploadDir) . DIRECTORY_SEPARATOR . $newFileName;
             if ($model->file->saveAs($newFullFileName)) {
                 return ['id' => $oldFileName, 'url' => \Yii::$app->request->getHostInfo() . str_replace('@webroot', '', $module->uploadDir) . '/' . $newFileName];
             }
         } else {
             \Yii::$app->response->statusCode = 500;
             return $model->getFirstError('file');
         }
     } elseif (\Yii::$app->request->isDelete && $file) {
         return true;
     }
     throw new BadRequestHttpException();
 }
 public function actionTarget()
 {
     $request = Yii::$app->request;
     $uploadedFile = \yii\web\UploadedFile::getInstanceByName('file');
     if ($uploadedFile && $request->post('album_id')) {
         $album = \app\modules\photo\models\Albums::findOne($request->post('album_id'));
         if (!$album || !$album->canEdit()) {
             throw new \app\components\exceptions\FormException('Nie możesz dodawać zdjęć do tego albumu.', 403);
         }
         $album->uploadsPath = $this->module->params['uploadsPath'];
         $trans = Yii::$app->db->beginTransaction();
         try {
             $photo = new \app\modules\photo\models\Photos();
             $photo->album_id = $album->id;
             $photo->albumPath = $album->getPathToAlbum();
             $photo->imageFile = $uploadedFile;
             if ($photo->validate() && $photo->save()) {
                 if (!$photo->upload()) {
                     throw new \app\components\exceptions\FormException('Błąd podczas zapisu pliku w ' . $this->getFilePath() . ': ' . print_r($this->errors, true));
                 }
                 $trans->commit();
             } else {
                 throw new \app\components\exceptions\FormException('Problem podczas zapisu danych pliku.');
             }
         } catch (\yii\base\Exception $exc) {
             $trans->rollBack();
             echo $exc->getMessage();
             echo $exc->getTraceAsString();
         }
     } else {
         throw new \app\components\exceptions\FormException('Nie odebrano poprawnie danych.');
     }
     Yii::$app->end();
 }
Пример #6
0
 /**
  * 
  * @return type
  * @throws BadRequestHttpException
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         if (!empty($this->getParamName) && Yii::$app->getRequest()->get($this->getParamName)) {
             $this->paramName = Yii::$app->getRequest()->get($this->getParamName);
         }
         $file = UploadedFile::getInstanceByName($this->paramName);
         $model = new DynamicModel(compact('file'));
         $model->addRule('file', $this->_validator, $this->validatorOptions);
         if ($model->validate()) {
             if ($this->unique === true) {
                 $model->file->name = uniqid() . (empty($model->file->extension) ? '' : '.' . $model->file->extension);
             }
             $result = $model->file->saveAs($this->path . $model->file->name) ? ['key' => $model->file->name, 'caption' => $model->file->name, 'name' => $model->file->name] : ['error' => 'Can\'t upload file'];
         } else {
             $result = ['error' => $model->getErrors()];
         }
         if (Yii::$app->getRequest()->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
         }
         return $result;
     } else {
         throw new BadRequestHttpException('Only POST is allowed');
     }
 }
Пример #7
0
 public function actionSaveTemplate()
 {
     $request = Yii::$app->request;
     if ($request->isPost) {
         $model_upload = new UploadForm();
         $model_upload->file = UploadedFile::getInstanceByName('DocContent');
         if ($model_upload->validate()) {
             $id = $request->get("id");
             $model = DocumentTemplate::find()->where(["DocumentID" => $id])->one();
             if (!$model) {
                 $model = new DocumentTemplate();
             }
             $model->DocumentID = $id;
             $model->URL = "/uploads/print/template/test.doc";
             $model->save();
             $model->URL = "/uploads/print/template/" . $model->ID . ".doc";
             $model->save();
             $path = dirname(Yii::$app->basePath) . $model->URL;
             if ($model_upload->file->saveAs($path)) {
                 echo "success";
                 exit;
             }
         } else {
             echo "failed";
         }
     }
 }
Пример #8
0
 public function signup($post_data)
 {
     $user = new Users();
     $user->username = $post_data['username'];
     $user->username_rus = $post_data['runame'];
     $user->pasport_code = (int) $post_data['passport_code'];
     $user->ref_id = $post_data['user_ref_id'];
     $user->password = Yii::$app->getSecurity()->generatePasswordHash($post_data['password']);
     $user->social_role = 'N';
     $user->ip = $_SERVER['REMOTE_ADDR'];
     $this->photo = UploadedFile::getInstanceByName('userfile');
     if ($this->photo) {
         $user->avatar = $this->photo->baseName . '.' . $this->photo->extension;
     }
     if ($user->save()) {
         if ($this->photo) {
             mkdir('./images/users_photo/' . $user->id . '/avatar/', 0777, true);
             //            chmod('./images/users_photo/' . $user->id, 0777);
             //            chmod('./images/users_photo/' . $user->id . '/avatar/', 0777);
             $this->photo->saveAs('images/users_photo/' . $user->id . '/avatar/' . $this->photo->baseName . '.' . $this->photo->extension);
         }
         if (Yii::$app->session->has('guest')) {
             $guest = Yii::$app->session->get('guest');
             UsersParameters::syncFromGuestsParameters($user->id, $guest->id);
             UsersStats::syncFromGuestsStats($user->id, $guest->id);
             Yii::$app->session->remove('guest');
         }
         Yii::$app->user->login($user, 3600 * 24 * 30);
         return true;
     } else {
         return false;
     }
 }
 public function run($type, $behavior, $id)
 {
     $remove = Yii::$app->request->post('remove', false);
     if (!isset($this->types[$type])) {
         throw new BadRequestHttpException('Specified model not found');
     }
     /** @var ActiveRecord $targetModel */
     $pkNames = call_user_func([$this->types[$type], 'primaryKey']);
     $pkValues = explode($this->pkGlue, $id);
     $pk = array_combine($pkNames, $pkValues);
     $targetModel = call_user_func([$this->types[$type], 'findOne'], $pk);
     /** @var ImageAttachmentBehavior $behavior */
     $behavior = $targetModel->getBehavior($behavior);
     if ($remove) {
         $behavior->removeImages();
         $behavior->extension = 'gif';
         $behavior->removeImages();
         return Json::encode(array());
     } else {
         /** @var UploadedFile $imageFile */
         $imageFile = UploadedFile::getInstanceByName('image');
         $extension = null;
         if ($imageFile->type == 'image/gif') {
             $extension = 'gif';
         }
         $behavior->setImage($imageFile->tempName, $extension);
         return Json::encode(array('previewUrl' => $behavior->getUrl('preview')));
     }
 }
 public function actionImport()
 {
     $imported = 0;
     $dropped = 0;
     $file = UploadedFile::getInstanceByName('filename');
     if ($file) {
         $lang = Yii::$app->request->post('lang');
         $content = file($file->tempName);
         foreach ($content as $line) {
             $transl = explode('@', $line);
             $oTranslation = Translation::findOne(['t_l_id' => $lang, 't_fr_id' => $transl[0]]);
             if ($oTranslation) {
                 $oTranslation->antworten = $transl[2];
                 $oTranslation->frage = $transl[1];
             } else {
                 $oTranslation = new Translation();
                 $oTranslation->t_fr_id = $transl[0];
                 $oTranslation->t_l_id = $lang;
                 $oTranslation->antworten = $transl[2];
                 $oTranslation->frage = $transl[1];
             }
             $oTranslation->save();
             $imported++;
         }
     }
     return $this->render('import', ['imported' => $imported, 'dropped' => $dropped]);
 }
Пример #11
0
 public function run()
 {
     try {
         //instance uploadfile
         $this->uploadfile = UploadedFile::getInstanceByName($this->postFieldName);
         if (null === $this->uploadfile) {
             throw new Exception("uploadfile {$this->postFieldName} not exist");
         }
         if (null !== $this->beforeValidate) {
             call_user_func($this->beforeValidate, $this);
         }
         $this->validate();
         if (null !== $this->afterValidate) {
             call_user_func($this->afterValidate, $this);
         }
         if (null !== $this->beforeSave) {
             call_user_func($this->beforeSave, $this);
         }
         $this->save();
         if ($this->afterSave !== null) {
             call_user_func($this->afterSave, $this);
         }
     } catch (Exception $e) {
         $this->output['error'] = true;
         $this->output['msg'] = $e->getMessage();
     }
     Yii::$app->response->format = 'json';
     return $this->output;
 }
Пример #12
0
 public function actionUpload()
 {
     $seedModel = new UploadedSeedFile();
     if (Yii::$app->request->isPost) {
         $response = [];
         $seedModel->torrentFile = UploadedFile::getInstanceByName('torrentFile');
         $seedModel->attributes = Yii::$app->request->post();
         Yii::info($seedModel->torrentFile);
         $retval = null;
         $res = $seedModel->upload($retval);
         Yii::info($retval);
         $response['result'] = $retval;
         if ($retval == 'succeed') {
             $response['extra'] = $res->attributes;
         } elseif ($retval == 'exists') {
             $response['extra'] = $res->seed_id;
         } else {
             $response['extra'] = $seedModel->errors;
         }
     } else {
         $response['result'] = 'failed';
         $response['extra'] = 'method not post';
     }
     Yii::info($response);
     return $response;
 }
Пример #13
0
 /**
  * Загрузка файлов по имени. Возвращает массив путей к загруженным файлам, относительно 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;
 }
Пример #14
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         $file = UploadedFile::getInstanceByName($this->uploadParam);
         $model = new DynamicModel(compact($this->uploadParam));
         $model->addRule($this->uploadParam, 'image', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'wrongExtension' => Yii::t('cropper', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate();
         if ($model->hasErrors()) {
             $result = ['error' => $model->getFirstError($this->uploadParam)];
         } else {
             $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension;
             $request = Yii::$app->request;
             $width = $request->post('width', $this->width);
             $height = $request->post('height', $this->height);
             $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($width, $height));
             if ($image->save($this->path . $model->{$this->uploadParam}->name)) {
                 $result = ['filelink' => $this->url . $model->{$this->uploadParam}->name];
             } else {
                 $result = ['error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE')];
             }
         }
         Yii::$app->response->format = Response::FORMAT_JSON;
         return $result;
     } else {
         throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST'));
     }
 }
 public function run()
 {
     if (Yii::$app->request->isPost) {
         $model = new ImageForm();
         $model->image = UploadedFile::getInstanceByName('image');
         if ($model->validate()) {
             if ($model->upload()) {
                 list($width, $height) = getimagesize($model->url);
                 return Json::encode(['size' => [$width, $height], 'url' => Yii::$app->request->baseUrl . '/' . $model->url]);
             }
         } else {
             $errors = [];
             $modelErrors = $model->getErrors();
             foreach ($modelErrors as $field => $fieldErrors) {
                 foreach ($fieldErrors as $fieldError) {
                     $errors[] = $fieldError;
                 }
             }
             if (empty($errors)) {
                 $errors = ['Unknown file upload validation error!'];
             }
             return Json::encode(['errors' => $errors]);
         }
     }
 }
Пример #16
0
 public function actionIndex()
 {
     $file = UploadedFile::getInstanceByName('imgFile');
     $basePath = dirname(\Yii::getAlias('@common'));
     $date = date("Y{$this->separator}m", time());
     $uploadPath = "../uploads/Attachment/{$date}";
     if (!is_dir($basePath . "/" . $uploadPath)) {
         FileHelper::createDirectory($basePath . "/" . $uploadPath);
     }
     if (preg_match('/(\\.[\\S\\s]+)$/', $file->name, $match)) {
         $filename = md5(uniqid(rand())) . $match[1];
     } else {
         $filename = $file->name;
     }
     $uploadData = ['type' => $file->type, 'name' => $filename, 'size' => $file->size, 'path' => "/" . $uploadPath, 'module' => null, 'controller' => null, 'action' => null, 'user_id' => \Yii::$app->user->isGuest ? 0 : \Yii::$app->user->identity->id];
     $module = \Yii::$app->controller->module;
     Upload::$db = $module->db;
     $model = new Upload();
     $model->setAttributes($uploadData);
     $model->validate();
     if ($model->save() && $file->saveAs($basePath . '/' . $uploadPath . '/' . $filename)) {
         return Json::encode(array('error' => 0, 'url' => "/" . $uploadPath . '/' . $filename, 'id' => $model->id, 'name' => $file->name));
     } else {
         return Json::encode(array('error' => 1, 'msg' => Json::encode($model->getErrors())));
     }
 }
Пример #17
0
 public static function save($field_name = null)
 {
     if (0 == count($_FILES)) {
         throw new Exception('没有文件被上传');
     }
     if (!$field_name) {
         $field_name = array_keys($_FILES)[0];
     }
     if (!isset($_FILES[$field_name])) {
         throw new Exception('指定上传字段不存在');
     }
     try {
         $uploader = UploadedFile::getInstanceByName($field_name);
         $basepath = realpath(\Yii::$app->basePath . '/../cdn');
         $from = ArrayHelper::getValue($_POST, 'from', 'imgs');
         $path = sprintf('%s/%s/%s', $basepath, $from, date('Y/m/d'));
         if (!is_dir($path)) {
             mkdir($path, 0777, true);
         }
         $filename = substr(md5('nisnaker' . microtime()), 16);
         $new_file = sprintf('%s/%s.%s', $path, $filename, $uploader->extension);
         if ($uploader->saveAs($new_file)) {
             $url = substr($new_file, strlen($basepath));
             return 'http://' . \Yii::$app->params['site.cdn.domain'] . $url;
         } else {
             throw new Exception('文件上传失败');
         }
     } catch (Exception $e) {
         throw $e;
     }
 }
Пример #18
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         $file = UploadedFile::getInstanceByName($this->incomingFieldName);
         $model = DynamicModel::validateData(compact('file'));
         $model->addRule('file', $this->isImage ? 'image' : 'file', $this->validationOptions);
         if ($model->hasErrors()) {
             return $this->getResult(false, implode('; ', $model->getErrors('file')));
         } else {
             if ($this->isUseUniqueFileNames) {
                 $filename = uniqid($this->isUseFileNamesAsPrefix ? $file->baseName : $this->customPrefix) . '.' . $file->extension;
             } else {
                 $filename = $file->baseName . '.' . $file->extension;
             }
             if (@$file->saveAs($this->savePath . $filename)) {
                 return $this->getResult(true, '', ['access_link' => $this->accessUrl . $filename]);
             }
             return $this->getResult(false, 'File can\'t be placed to destination folder');
         }
     } else {
         throw new BadRequestHttpException('Only Post request allowed for this action!');
     }
     $uploads_dir = '/var/tmp';
     if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
         $tmp_name = $_FILES["file"]["tmp_name"];
         $name = $_FILES["file"]["name"];
         move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}");
     }
     return ['success' => true, 'value' => '/uploads/some.file.txt'];
 }
Пример #19
0
 /**
  * @return string
  * @throws \yii\base\Exception
  */
 public function actionSaveImg()
 {
     $croppicForm = new CroppicForm();
     $croppicForm->file = UploadedFile::getInstanceByName('img');
     if ($croppicForm->file && $croppicForm->validate()) {
         $path = Cloud::getInst()->cloudPath;
         $pathWeb = Cloud::getInst()->webCloudPath;
         FileHelper::createDirectory($path);
         $croppicForm->file->name = uniqid('big_') . '.' . $croppicForm->file->extension;
         $croppicForm->file->saveAs($path . $croppicForm->file->baseName . '.' . $croppicForm->file->extension);
         list($width, $height) = getimagesize($path . $croppicForm->file->name);
         $json['status'] = 'success';
         $json['url'] = Url::to($pathWeb . $croppicForm->file->name, true);
         $json['width'] = $width;
         $json['height'] = $height;
         return Json::encode($json);
     }
     $json['status'] = 'error';
     $errors = $croppicForm->getFirstErrors();
     if ($errors) {
         $json['message'] = reset($errors);
     } else {
         $json['message'] = 'Oops, something went wrong. Please try again!';
     }
     return Json::encode($json);
 }
 public function actionImport()
 {
     set_time_limit(0);
     ini_set("memory_limit", '512M');
     $uploadfile = UploadedFile::getInstanceByName('Filedata');
     if (!$uploadfile || $uploadfile->getHasError()) {
         return 0;
     }
     $data = $this->getExcelData($uploadfile->tempName);
     //$data = $this->getExcelData('/Users/jsj/workspace/cnpc/test.xls');
     $trans = \Yii::$app->db->beginTransaction();
     try {
         foreach ($data as $item) {
             $columns = array_keys($item);
             $value = array_values($item);
             $updates = array_map(function ($k, $v) {
                 return $k . "='" . $v . "'";
             }, $columns, $value);
             $sql = "insert into jumper_info (" . implode(',', $columns) . ") values('" . implode("','", $value) . "') ON DUPLICATE KEY update " . implode(',', $updates);
             $result = \Yii::$app->db->createCommand($sql)->execute();
         }
         $trans->commit();
     } catch (Exception $e) {
         $trans->rollBack();
         throw $e;
     }
     return 1;
 }
Пример #21
0
 public function actionCreate()
 {
     $file = UploadedFile::getInstanceByName($this->form_params);
     if (!$file) {
         throw new ErrorException("media file can't null", 400);
     }
     if ("jpg" != $file->extension) {
         throw new ErrorException("media extension must be jpg", 400);
     }
     $uuid = uniqid();
     $filename = "IMG_" . $uuid . "." . $file->extension;
     try {
         $file->saveAs($this->path . $filename);
     } catch (\Exception $e) {
         throw new ErrorException("The path can't writen", 500);
     }
     try {
         $media = new Media();
         $media->id = $uuid;
         $media->name = urldecode($file->name);
         $media->type = $file->extension;
         $media->size = $file->size;
         $media->newname = $filename;
         $media->user = Yii::$app->user->identity->username;
         $media->save();
     } catch (\Exception $e) {
         throw new ErrorException("Write db error!", 500);
     }
     return ['code' => 200, 'message' => "ok", 'media_id' => $uuid];
 }
Пример #22
0
 /**
  *   上传头像
  *   图片上传成功后做标记,渲染裁剪功能,裁剪后坐标传送给Headcut,Headcut进行裁剪,保存图片,标记。
  */
 public function actionIndex()
 {
     $accessKey = 'l5Y69nZUNTSeeqJx1LqCJP1KuLWIGU_3JVZXLzN-';
     $secretKey = '6-4HOEBkNlJpo_TuFrM9W8ZEjytRZAYjuiG0F8Df';
     $auth = new Auth($accessKey, $secretKey);
     $bucketMgr = new BucketManager($auth);
     $bucket = 'colfans-uploads-public';
     $key = 'fun.jpg';
     list($ret, $err) = $bucketMgr->stat($bucket, $key);
     echo "\n====> stat result: \n";
     if ($err !== null) {
         var_dump($err);
     } else {
         var_dump($ret);
     }
     if (!empty($_FILES['headpic'])) {
         $user = User::findByUsername(Yii::$app->user->identity->username);
         $image = UploadedFile::getInstanceByName('headpic');
         $imageName = $user->id . '_' . time() . '.' . $image->getExtension();
         if ($image->saveAs('uploads/head/' . $imageName)) {
             // file is uploaded successfully
             echo 'yes';
             die;
         } else {
             echo 'no';
             die;
         }
     } else {
         return $this->render('headupload', ['title' => '个人资料', 'category' => '账号管理', 'subcate' => '个人资料']);
     }
 }
Пример #23
0
 public function uploadImage($route, $gallery_types_id, $gallery_groups_id)
 {
     $type = (new Query())->select('*')->from($this->tableTypes)->where(['id' => $gallery_types_id])->createCommand()->queryOne();
     $route = preg_replace('/\\/$/', '', $route);
     $destination = preg_replace('/\\/$/', '', $type['destination']);
     if (!is_dir($route . $destination)) {
         if (!mkdir($route . $destination)) {
             return ['success' => false, 'message' => 'Failed to add directory'];
         }
     }
     $imageFile = UploadedFile::getInstanceByName('image');
     $image = (new Query())->select('*')->from($this->tableImages)->where(['gallery_groups_id' => $gallery_groups_id])->andWhere(['name' => $imageFile->baseName . '.' . $imageFile->extension])->createCommand()->queryOne();
     if ($image) {
         return ['success' => false, 'message' => 'File downloaded previously in this group'];
     }
     $src_file = $route . $destination . '/' . $imageFile->baseName . '.' . $imageFile->extension;
     $imageFile->saveAs($src_file, true);
     $size = $this->getSize($src_file, $type);
     $image_small = $this->renderFilename($route . $destination, $imageFile->extension);
     $image_large = $this->renderFilename($route . $destination, $imageFile->extension);
     Image::$driver = [Image::DRIVER_GD2];
     Image::thumbnail($src_file, $size['small_width'], $size['small_height'])->save($route . $destination . '/' . $image_small . '.' . $imageFile->extension, ['quality' => $type['quality']]);
     Image::thumbnail($src_file, $size['large_width'], $size['large_height'])->save($route . $destination . '/' . $image_large . '.' . $imageFile->extension, ['quality' => $type['quality']]);
     unlink($src_file);
     $query = new Query();
     $query->createCommand()->insert($this->tableImages, ['gallery_groups_id' => $gallery_groups_id, 'small' => $destination . '/' . $image_small . '.' . $imageFile->extension, 'large' => $destination . '/' . $image_large . '.' . $imageFile->extension, 'name' => $imageFile->baseName . '.' . $imageFile->extension, 'seq' => $this->getLastSequence($gallery_groups_id) + 1])->execute();
     return ['success' => true, 'gallery_images_id' => Yii::$app->db->getLastInsertID(), 'gallery_groups_id' => $gallery_groups_id, 'small' => $destination . '/' . $image_small . '.' . $imageFile->extension, 'large' => $destination . '/' . $image_large . '.' . $imageFile->extension];
 }
Пример #24
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $result = ['err' => 1, 'msg' => 'swfupload init'];
     if (Yii::$app->request->isPost) {
         $data = Yii::$app->request->get('data');
         $data = Json::decode(base64_decode($data));
         $url = $data['url'];
         $path = $data['path'];
         $params = $data['params'];
         $callback = $data['callback'];
         $file = UploadedFile::getInstanceByName('FileData');
         $model = new DynamicModel(compact('file'));
         $model->addRule('file', 'image', [])->validate();
         if ($model->hasErrors()) {
             $result['msg'] = $model->getFirstError('file');
         } else {
             if ($model->file->extension) {
                 $model->file->name = uniqid() . '.' . $model->file->extension;
             }
             if ($model->file->saveAs($path . $model->file->name)) {
                 $result['err'] = 0;
                 $result['msg'] = 'success';
                 $result['url'] = $model->file->name;
                 $result['params'] = $params;
                 $result['callback'] = $callback;
             } else {
                 $result['msg'] = $model->getFirstError('file save error!');
             }
         }
     }
     Yii::$app->response->format = Response::FORMAT_JSON;
     return $result;
 }
Пример #25
0
 /**
  * 无模型上传图片
  * @param string $attribute 字段名
  * @param string $dir uploads目录下的子目录名称(不存在自动创建)
  * @return string
  */
 public static function uploadEditor($attribute, $dir = 'other')
 {
     $upload = UploadedFile::getInstanceByName($attribute);
     $pathName = self::savePath($upload->extension, $dir);
     /* 保存图片 */
     $upload->saveAs($pathName);
     return $pathName;
 }
Пример #26
0
 public static function getInstanceByName($name, $res = 'common')
 {
     $up = new self();
     $up->uploader = UploadedFile::getInstanceByName($name);
     $up->res = $res;
     $up->setPathName();
     return $up;
 }
Пример #27
0
 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 . ')'];
     }
 }
Пример #28
0
 public function actionFileupload()
 {
     $name = Yii::$app->request->post('name');
     if ($name && ($file = UploadedFile::getInstanceByName($name)) !== null) {
         $fileName = time() . mt_rand(1000, 10000) . '.' . $file->extension;
         $file->saveAs('../uploads/' . $fileName);
         echo json_encode(['append' => false, 'name' => $fileName, 'extra' => ['filename' => $fileName]]);
     }
 }
Пример #29
-1
 public function beforeValidate()
 {
     if (parent::beforeValidate()) {
         $this->file = UploadedFile::getInstanceByName('file');
         return true;
     }
     return false;
 }
Пример #30
-2
 /**
  * 头像上传
  *
  * @param string $name 图片标识
  * @param array $options 图片截取选项
  *  - pointer: 坐标, [x, y]
  *  - size: 宽高等比尺寸
  *
  *  @return boolean
  */
 public function upload($name, $options = [])
 {
     // 临时测试数据
     /*
             $options = [
        'pointer' => [100, 100],
        'size' => 200,
             ];
     */
     $file = UploadedFile::getInstanceByName($name);
     $result = false;
     $allowExtNames = ['jpg', 'jpeg', 'png', 'gif'];
     if ($file && $file->error === self::UPLOAD_SUCCESS_FLAG) {
         $extName = $file->getExtension();
         if (!in_array($extName, $allowExtNames)) {
             return $result;
         }
         $tmpFile = $this->process($file->tempName, $extName, $options);
         if ($tmpFile) {
             $result = $this->upload2Oss($tmpFile);
         }
         unlink($this->tmpPath . $tmpFile);
     }
     return $result;
 }