本文整理汇总了PHP中yii\web\UploadedFile::getInstanceByName方法的典型用法代码示例。如果您正苦于以下问题:PHP UploadedFile::getInstanceByName方法的具体用法?PHP UploadedFile::getInstanceByName怎么用?PHP UploadedFile::getInstanceByName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\web\UploadedFile
的用法示例。
在下文中一共展示了UploadedFile::getInstanceByName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
/**
* @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: run
/**
* @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: actionUpload
/**
* 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;
}
示例4: actionData
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();
}
示例5: actionTarget
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: run
/**
*
* @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: actionSaveTemplate
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: signup
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;
}
}
示例9: run
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')));
}
}
示例10: actionImport
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: run
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: actionUpload
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: uploadFiles
/**
* Загрузка файлов по имени. Возвращает массив путей к загруженным файлам, относительно 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: run
/**
* @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'));
}
}
示例15: run
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]);
}
}
}