本文整理汇总了PHP中yii\web\UploadedFile::getInstance方法的典型用法代码示例。如果您正苦于以下问题:PHP UploadedFile::getInstance方法的具体用法?PHP UploadedFile::getInstance怎么用?PHP UploadedFile::getInstance使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\web\UploadedFile
的用法示例。
在下文中一共展示了UploadedFile::getInstance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: beforeSave
function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$file = UploadedFile::getInstance($this, 'image');
if ($file && $file->error === UPLOAD_ERR_OK) {
// Ищем, есть ли уже такой загруженный файл
$file_model = Files::findOne(['hash' => md5_file($file->tempName)]);
if ($file_model) {
$file_model->repeats++;
} else {
$file_model = new Files();
$file_model->saveImageFile($file);
$file_model->repeats = 1;
}
$file_model->save();
$this->file_id = $file_model->id;
} else {
$this->addError('image', 'Невозможно загрузить файл');
return false;
}
return true;
} else {
return false;
}
}
示例2: actionEdit
public function actionEdit($id)
{
if (!($model = Item::findOne($id))) {
return $this->redirect(['/admin/' . $this->module->id]);
}
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
} else {
if (isset($_FILES) && $this->module->settings['articleThumb']) {
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->image && $model->validate(['image'])) {
$model->image = Image::upload($model->image, 'sections');
} else {
$model->image = $model->oldAttributes['image'];
}
}
if ($model->save()) {
$this->flash('success', Yii::t('easyii/sections', 'Article updated'));
return $this->redirect(['/admin/' . $this->module->id . '/items/edit', 'id' => $model->primaryKey]);
} else {
$this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
return $this->refresh();
}
}
} else {
return $this->render('edit', ['model' => $model]);
}
}
示例3: actionAvatar
public function actionAvatar()
{
if (\Yii::$app->request->get('do') == 'edit') {
$model = new AvatarForm();
if (\Yii::$app->request->isPost) {
$model->avatar = UploadedFile::getInstance($model, 'avatar');
if ($model->validate()) {
$uploadDir = 'upload/avatar/' . date('Ym');
if (!file_exists($uploadDir)) {
mkdir($uploadDir);
}
$uploadFile = $uploadDir . '/' . $model->avatar->name;
$model->avatar->saveAs($uploadFile);
$model->avatar->name = '/' . $uploadFile;
list($width, $height) = getimagesize($uploadFile);
return $this->ajaxReturn(['avatar' => $model->avatar->name, 'width' => $width, 'height' => $height]);
}
}
return $this->render('/user/profile/avatar_edit', ['model' => $model]);
} else {
if (\Yii::$app->request->get('do') == 'save') {
$avatar = \Yii::$app->request->post('avatar');
$width = intval(\Yii::$app->request->post('width'));
$height = intval(\Yii::$app->request->post('height'));
$img = $this->thumb($avatar, $width, $height);
$coords = explode(',', \Yii::$app->request->post('coords'));
$img = $this->crop($img, $coords[0], $coords[1], [$coords[2], $coords[3]]);
Profile::saveAvatar($img);
return $this->ajaxReturn(['msg' => '保存成功']);
}
}
return $this->redirect('/user/profile/avatar');
}
示例4: actionCreate
public function actionCreate()
{
$model = new Import();
if ($model->load(Yii::$app->request->post())) {
$file_path = \yii\web\UploadedFile::getInstance($model, 'file_path');
if (!empty($file_path)) {
$model->file_path = \yii\web\UploadedFile::getInstance($model, 'file_path');
$ext = FileHelper::getExtention($model->file_path);
if (!empty($ext)) {
$fileDir = Yii::$app->controller->module->id . '/' . date('Y/m/d/');
$fileName = uniqid() . StringHelper::asUrl(Yii::$app->controller->module->id) . '.' . $ext;
$folder = Yii::$app->params['uploadPath'] . '/' . Yii::$app->params['uploadDir'] . '/' . $fileDir;
FileHelper::createDirectory($folder);
$model->file_path->saveAs($folder . $fileName);
$model->file_path = $fileDir . $fileName;
}
}
if ($model->save()) {
return $this->redirect(['update', 'id' => (string) $model->_id]);
}
}
Yii::$app->view->title = Yii::t($this->module->id, 'Create');
Yii::$app->view->params['breadcrumbs'][] = ['label' => Yii::t($this->module->id, 'Import'), 'url' => ['index']];
Yii::$app->view->params['breadcrumbs'][] = Yii::$app->view->title;
return $this->render('create', ['model' => $model]);
}
示例5: afterUpdate
public function afterUpdate()
{
try {
if ($this->seoText->load(Yii::$app->request->post())) {
$this->seoText->setAttributes(['_image' => UploadedFile::getInstance($this->seoText, '_image')]);
// if(!$this->seoText->isEmpty()){
if ($this->seoText->save()) {
if ($this->seoText->_image) {
$old = $this->seoText->ogImage;
$photo = new Photo();
$photo->class = get_class($this->seoText);
$photo->item_id = $this->seoText->seotext_id;
$photo->image = $this->seoText->_image;
if ($photo->image && $photo->validate(['image'])) {
$photo->image = Image::upload($photo->image, 'photos', Photo::PHOTO_MAX_WIDTH);
if ($photo->image) {
if ($photo->save()) {
$old->delete();
} else {
@unlink(Yii::getAlias('@webroot') . str_replace(Url::base(true), '', $photo->image));
}
} else {
}
}
}
}
}
} catch (UnknownMethodException $e) {
}
}
示例6: actionIndex
public function actionIndex()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
$ext = $model->file->extension;
$file_name = $model->file->baseName . '.' . $model->file->extension;
if ($model->upload()) {
if ($ext == 'csv') {
$erros = $this->ConverterCSV($file_name);
}
if ($ext == 'txt') {
$erros = $this->ConverterTXT($file_name);
}
if ($erros == NULL) {
$link = Html::a('Ver em produtos', ['/produto'], ['class' => 'btn btn-primary']);
\Yii::$app->getSession()->setFlash('success', 'Dados importados! ' . $link . '');
} else {
if (is_array($erros)) {
$texto_erro = "";
foreach ($erros as $erro) {
$texto_erro .= $erro . '<br/>';
}
\Yii::$app->getSession()->setFlash('error', $texto_erro);
}
}
}
}
return $this->render('index', ['model' => $model]);
}
示例7: actionIndex
public function actionIndex()
{
$id = Yii::$app->request->get('id');
$modelName = Yii::$app->request->get('model');
if (!empty($id)) {
$model = $modelName::findOne($id);
if ($model) {
// $model->gallery = \yii\web\UploadedFile::getInstance($model, 'gallery');
$image = \yii\web\UploadedFile::getInstance($model, 'gallery');
$ext = FileHelper::getExtention($image);
if (!empty($ext)) {
// Thêm validate ext ____________________________
$file_id = uniqid();
$fileDir = Yii::$app->controller->module->id . '/' . date('Y/m/d/');
$fileName = $file_id . '.' . $ext;
$folder = Yii::$app->params['uploadPath'] . '/' . Yii::$app->params['uploadDir'] . '/' . $fileDir;
FileHelper::createDirectory($folder);
$image->saveAs($folder . $fileName);
$output = ["out" => ['file_id' => $file_id, 'item_id' => Yii::$app->controller->module->id]];
if (empty($model->gallery)) {
$model->gallery = $fileDir . $fileName;
} else {
$model->gallery .= ',' . $fileDir . $fileName;
}
$model->save();
echo json_encode($output);
}
}
}
}
示例8: actionEdit
public function actionEdit($id)
{
if (!($model = Category::findOne($id))) {
return $this->redirect(['/admin/catalog']);
}
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
} else {
if (isset($_FILES) && $this->module->settings['categoryThumb']) {
$model->thumb = UploadedFile::getInstance($model, 'thumb');
if ($model->thumb && $model->validate(['thumb'])) {
$model->thumb = Image::upload($model->thumb, 'catalog', $this->module->settings['categoryThumbWidth'], $this->module->settings['categoryThumbHeight'], $this->module->settings['categoryThumbCrop']);
} else {
$model->thumb = $model->oldAttributes['thumb'];
}
}
if ($model->save()) {
$this->flash('success', Yii::t('easyii/catalog', 'Category updated'));
} else {
$this->flash('error', Yii::t('easyii', 'Update error. {0}', $model->formatErrors()));
}
return $this->refresh();
}
} else {
return $this->render('edit', ['model' => $model]);
}
}
示例9: beforeValidate
/**
* Attaches uploaded file to owner.
*/
public function beforeValidate()
{
if (!($file = UploadedFile::getInstance($this->owner, $this->fileField))) {
return true;
}
$this->owner->{$this->fileField} = $file;
}
示例10: actionProductpic
/**
* 上传商品图片
*/
public function actionProductpic()
{
$user_id = \Yii::$app->user->getId();
$p_params = Yii::$app->request->get();
$product = Product::findOne($p_params['id']);
if (!$product) {
throw new NotFoundHttpException(Yii::t('app', 'Page not found'));
}
$picture = new UploadForm();
$picture->file = UploadedFile::getInstance($product, 'product_s_img');
if ($picture->file !== null && $picture->validate()) {
Yii::$app->response->getHeaders()->set('Vary', 'Accept');
Yii::$app->response->format = Response::FORMAT_JSON;
$response = [];
if ($picture->productSave()) {
$response['files'][] = ['name' => $picture->file->name, 'type' => $picture->file->type, 'size' => $picture->file->size, 'url' => '/' . $picture->getImageUrl(), 'thumbnailUrl' => '/' . $picture->getOImageUrl(), 'deleteUrl' => Url::to(['/uploadfile/deletepropic', 'id' => $picture->getID()]), 'deleteType' => 'POST'];
} else {
$response[] = ['error' => Yii::t('app', '上传错误')];
}
@unlink($picture->file->tempName);
} else {
if ($picture->hasErrors()) {
$response[] = ['error' => '上传错误'];
} else {
throw new HttpException(500, Yii::t('app', '上传错误'));
}
}
return $response;
}
示例11: actionCreate
/**
* Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new User();
try {
if ($model->load($_POST)) {
$model->password = md5($model->password);
$image = UploadedFile::getInstance($model, 'photo_url');
if ($image != NULL) {
# store the source file name
$model->photo_url = $image->name;
$extension = end(explode(".", $image->name));
# generate a unique file name
$model->photo_url = Yii::$app->security->generateRandomString() . ".{$extension}";
# the path to save file
$path = Yii::getAlias("@app/web/uploads/") . $model->photo_url;
$image->saveAs($path);
} else {
$model->photo_url = "default.png";
}
$model->save();
return $this->redirect(Url::previous());
} elseif (!\Yii::$app->request->isPost) {
$model->load($_GET);
}
} catch (\Exception $e) {
$msg = isset($e->errorInfo[2]) ? $e->errorInfo[2] : $e->getMessage();
$model->addError('_exception', $msg);
}
return $this->render('create', ['model' => $model]);
}
示例12: actionUpload
public function actionUpload($model, $primaryKey)
{
$results = [];
$modelImage = new Image();
$modelImage->model = $model;
$modelImage->primaryKey = $primaryKey;
$filePath = $modelImage->getFilePath();
if (Yii::$app->request->isPost) {
$modelImage->file = UploadedFile::getInstance($modelImage, 'file');
if ($modelImage->file && $modelImage->validate()) {
$filename = $modelImage->file->name;
$modelImage->src = $filename;
$modelImage->position = $modelImage->nextPosition;
$modelImage->save();
$image = \Yii::$app->image->load($modelImage->file->tempName);
$image->resize(2592, 1728, \yii\image\drivers\Image::AUTO);
if ($image->save($filePath . '/' . $filename)) {
$imagePath = $filePath . '/' . $filename;
$result = ['name' => $filename, 'size' => filesize($filePath . '/' . $filename), 'url' => $imagePath, 'thumbnailUrl' => $modelImage->resize('100x100'), 'deleteUrl' => Url::to(['/core/image/delete', 'id' => $modelImage->id]), 'deleteType' => "DELETE"];
$results[] = $result;
}
} else {
$results[] = (object) [$modelImage->file->name => false, 'error' => strip_tags(Html::error($modelImage, 'file')), 'extension' => $modelImage->file->extension, 'type' => $modelImage->file->type];
}
}
echo json_encode((object) ['files' => $results]);
}
示例13: actionImport
public function actionImport()
{
$field = ['fileImport' => 'File Import'];
$modelImport = DynamicModel::validateData($field, [[['fileImport'], 'required'], [['fileImport'], 'file', 'extensions' => 'xls,xlsx', 'maxSize' => 1024 * 1024]]);
if (Yii::$app->request->post()) {
$modelImport->fileImport = \yii\web\UploadedFile::getInstance($modelImport, 'fileImport');
if ($modelImport->fileImport && $modelImport->validate()) {
$inputFileType = \PHPExcel_IOFactory::identify($modelImport->fileImport->tempName);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($modelImport->fileImport->tempName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$baseRow = 2;
while (!empty($sheetData[$baseRow]['A'])) {
$model = new Mahasiswa();
$model->nama = (string) $sheetData[$baseRow]['B'];
$model->nim = (string) $sheetData[$baseRow]['C'];
$model->save();
//die(print_r($model->errors));
$baseRow++;
}
Yii::$app->getSession()->setFlash('success', 'Success');
} else {
Yii::$app->getSession()->setFlash('error', 'Error');
}
}
return $this->redirect(['index']);
}
示例14: add
public function add()
{
if ($this->validate()) {
$organization = new Organizations();
$organization->official_name = $this->official_name;
$organization->nice_name = $this->nice_name;
$organization->cyr_name = $this->cyr_name;
$organization->overdraft_limit = $this->overdraft;
$organization->outbalance_limit = $this->outbalance;
$organization->ratio = $this->ratio;
$logo_file = UploadedFile::getInstance($this, 'logo');
if ($logo_file) {
$file_name = $logo_file->baseName . '.' . $logo_file->extension;
$organization->logo = $file_name;
}
if ($organization->save()) {
if ($logo_file) {
$folder_path = Yii::$app->params['org_img_path'] . '/' . $organization->id;
mkdir($folder_path);
$logo_file->saveAs($folder_path . '/' . $file_name);
}
$this->addOwnersRelations($organization->id);
return true;
}
}
return false;
}
示例15: upload
public function upload($attribute)
{
if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) {
if (!$this->owner->isNewRecord) {
$this->delete($attribute);
}
$croppingFileName = md5($uploadImage->name . $this->quality . filemtime($uploadImage->tempName));
$croppingFileExt = strrchr($uploadImage->name, '.');
$croppingFileDir = substr($croppingFileName, 0, 2);
$croppingFileBasePath = Yii::getAlias($this->basePath) . $this->baseDir;
if (!is_dir($croppingFileBasePath)) {
mkdir($croppingFileBasePath, 0755, true);
}
$croppingFilePath = Yii::getAlias($this->basePath) . $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir;
if (!is_dir($croppingFilePath)) {
mkdir($croppingFilePath, 0755, true);
}
$croppingFile = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt;
$cropping = $_POST[$attribute . '-cropping'];
$imageTmp = Image::getImagine()->open($uploadImage->tempName);
$imageTmp->rotate($cropping['dataRotate']);
$image = Image::getImagine()->create($imageTmp->getSize());
$image->paste($imageTmp, new Point(0, 0));
$point = new Point($cropping['dataX'], $cropping['dataY']);
$box = new Box($cropping['dataWidth'], $cropping['dataHeight']);
$image->crop($point, $box);
$image->save($croppingFile, ['quality' => $this->quality]);
$this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt;
} elseif (isset($_POST[$attribute . '-remove']) && $_POST[$attribute . '-remove']) {
$this->delete($attribute);
} elseif (isset($this->owner->oldAttributes[$attribute])) {
$this->owner->{$attribute} = $this->owner->oldAttributes[$attribute];
}
}