本文整理汇总了PHP中yii\web\UploadedFile::getInstancesByName方法的典型用法代码示例。如果您正苦于以下问题:PHP UploadedFile::getInstancesByName方法的具体用法?PHP UploadedFile::getInstancesByName怎么用?PHP UploadedFile::getInstancesByName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\web\UploadedFile
的用法示例。
在下文中一共展示了UploadedFile::getInstancesByName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: actionUploadArchive
/**
* 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;
}
示例2: actionUpload
/**
* 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]);
}
示例3: actionUpload
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;
}
示例4: 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;
}
示例5: upload
/**
* 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;
}
示例6: actionIndex
/**
* 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;
}
示例7: prepareUpload
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 . ')'];
}
}
示例8: load
/**
* @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);
}
示例9: actionUpload
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.'));
}
}
示例10: actionAdditemimage
/**
* 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);
}
示例11: actionUpload
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);
}
示例12: run
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]);
}
}
示例13: run
/**
* 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 [];
}
示例14: saveEssay
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();
}
示例15: beforeValidate
/**
* 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;
});
}
}
}