本文整理汇总了PHP中CUploadedFile::getInstanceByName方法的典型用法代码示例。如果您正苦于以下问题:PHP CUploadedFile::getInstanceByName方法的具体用法?PHP CUploadedFile::getInstanceByName怎么用?PHP CUploadedFile::getInstanceByName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CUploadedFile
的用法示例。
在下文中一共展示了CUploadedFile::getInstanceByName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: actionUploadFile
public function actionUploadFile()
{
try {
$channelId = yii::app()->request->getParam('channelId');
$file = CUploadedFile::getInstanceByName('file');
$oldName = $file->getName();
$type = $file->getType();
$newName = date('Ymdhis') . '.' . $file->getExtensionName();
$attachment = new TSAttachment();
$attachment->Attachment_Old_Name = $oldName;
$attachment->Attachment_New_Name = $newName;
$attachment->Attachment_File_Type = $type;
$attachment->Attachment_Belong_Channel = $channelId;
$attachment->Attachment_Upload_Time = date("Y-m-d H:i:s", time());
$attachment->Attachment_Author = yii::app()->user->currUserName;
$attachment->Attachment_Path = Yii::getPathOfAlias('application.assets') . '/upload';
$uploadFile = Yii::getPathOfAlias('application.assets') . '/upload//' . $newName;
$flag = $file->saveAs($uploadFile);
$length = $attachment->save();
if ($flag && $length > 0) {
echo json_encode(array('flag' => 'SUCCESS', 'message' => '上传附件成功!'), JSON_UNESCAPED_UNICODE);
} else {
echo json_encode(array('flag' => 'ERROR', 'message' => '上传附件失败!'), JSON_UNESCAPED_UNICODE);
}
} catch (Exception $e) {
echo json_encode(array('flag' => 'Exception', 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
}
}
示例2: actionImage
/**
* Обработка изображения в форме тизера
*/
public function actionImage()
{
if ($file = CUploadedFile::getInstanceByName('file')) {
$file = $this->_uploadImage($file);
} elseif (isset($_REQUEST['url'])) {
$file = $this->_downloadImageByUrl($_REQUEST['url']);
}
if (isset($file)) {
if (!isset($file['error'])) {
$file = $this->_prepareImage($file);
}
echo json_encode(array('file' => array_diff_key($file, array('tmpName' => ''))));
Yii::app()->end();
} elseif (isset($_REQUEST['crop']) && isset($_REQUEST['fileName'])) {
try {
/** @var Image $img */
$img = Yii::app()->image->load(Yii::app()->params->docTmpPath . DIRECTORY_SEPARATOR . basename($_REQUEST['fileName']));
$outputFileName = CFile::createUniqueFileName(Yii::app()->params->imageBasePath, '.' . $img->image['ext'], 't_');
$img->resize((int) $_REQUEST['crop']['w'], (int) $_REQUEST['crop']['h'], Image::NONE)->crop(Yii::app()->params->teaserImageWidth, Yii::app()->params->teaserImageHeight, (int) $_REQUEST['crop']['y'], (int) $_REQUEST['crop']['x'])->save(Yii::app()->params->imageBasePath . DIRECTORY_SEPARATOR . $outputFileName);
} catch (CException $e) {
echo json_encode(array('error' => $e->getMessage()));
Yii::app()->end();
}
echo json_encode(array('fileName' => $outputFileName));
Yii::app()->end();
}
}
示例3: afterValidate
public function afterValidate($event)
{
$this->prepareDataDirectory();
$file = CUploadedFile::getInstanceByName($this->uploadInstance);
if ($file instanceof CUploadedFile && $file->getError() == UPLOAD_ERR_OK && !$this->Owner->hasErrors()) {
$uniqueFilename = P3StringHelper::generateUniqueFilename($file->getName());
$fullFilePath = $this->_fullDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
$relativeFilePath = $this->_relativeDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
if ($file->saveAs($fullFilePath)) {
#echo $fullFilePath;exit;
if (!$this->Owner->isNewRecord) {
$this->deleteFile($this->Owner->path);
}
if (!$this->Owner->title) {
$this->Owner->title = P3StringHelper::cleanName($file->name, 32);
}
$this->Owner->path = $relativeFilePath;
$this->Owner->mimeType = $file->type;
$this->Owner->size = $file->size;
$this->Owner->originalName = $file->name;
$this->Owner->md5 = md5_file($fullFilePath);
} else {
$this->Owner->addError('filePath', 'File uploaded failed!');
}
} else {
if ($this->Owner->isNewRecord) {
#$this->Owner->addError('filePath', 'No file uploaded!');
Yii::trace('No file uploaded!');
}
}
}
示例4: upload
public function upload($name = '')
{
if (!$name) {
throw new CException(Yii::t('no file name'));
}
$file = CUploadedFile::getInstanceByName($name);
if (!$file->hasError) {
//生成目录
$filename = md5(time()) . '.' . $file->extensionName;
$filepath = $this->getDirByTime() . DIRECTORY_SEPARATOR;
$allFilePath = $this->_dirPath . DIRECTORY_SEPARATOR . $filepath . $filename;
if (!$this->createDir($this->_dirPath . DIRECTORY_SEPARATOR . $filepath) || !is_writable($this->_dirPath . DIRECTORY_SEPARATOR . $filepath)) {
throw new CException(Yii::t('yii', 'dir can not create or can not writeable'));
}
if ($file->saveAs($allFilePath)) {
//获取图片宽和高
$picSize = getimagesize($allFilePath);
$imgInfo = array('name' => $file->name, 'filepath' => $filepath, 'filename' => $filename, 'filesize' => $file->size, 'type' => $file->extensionName, 'mark' => 'img', 'imgwidth' => $picSize[0], 'imgheight' => $picSize[1], 'create_time' => time());
//素材数据入库
$model = new Material();
$model->attributes = $imgInfo;
$model->save();
$imgInfo['id'] = $model->id;
return $imgInfo;
} else {
throw new CException(Yii::t('yii', 'file save error'));
}
} else {
throw new CException(Yii::t('yii', 'there is an error for upload ,error:{error}', array('{error}' => $file->error)));
}
}
示例5: actionUpload
/**
* Feltölt egy fájlt a megadott tantárgyhoz.
* @param int $id A tantárgy azonosítója
*/
public function actionUpload($id)
{
if (!Yii::app()->user->getId()) {
throw new CHttpException(403, 'A funkció használatához be kell jelentkeznie');
}
$id = (int) $id;
$file = CUploadedFile::getInstanceByName("to_upload");
if ($file == null) {
throw new CHttpException(404, 'Nem lett fájl kiválasztva a feltöltéshez');
}
$filename = $file->getName();
$localFileName = sha1($filename . microtime()) . "." . CFileHelper::getExtension($filename);
if (in_array(strtolower(CFileHelper::getExtension($filename)), Yii::app()->params["deniedexts"])) {
throw new CHttpException(403, ucfirst(CFileHelper::getExtension($filename)) . ' kiterjesztésű fájl nem tölthető fel a szerverre');
}
$model = new File();
$model->subject_id = $id;
$model->filename_real = $filename;
$model->filename_local = $localFileName;
$model->description = htmlspecialchars($_POST["description"]);
$model->user_id = Yii::app()->user->getId();
$model->date_created = new CDbExpression('NOW()');
$model->date_updated = new CDbExpression('NOW()');
$model->downloads = 0;
$model->save();
if ($file->saveAs("upload/" . $localFileName)) {
$this->redirect(Yii::App()->createUrl("file/list", array("id" => $id)));
}
}
示例6: run
public function run()
{
$file = CUploadedFile::getInstanceByName('file');
$path = $this->getUniquePath($this->filesDir(), $file->extensionName);
$file->saveAs($path);
echo CHtml::link($file->name, "http://" . $_SERVER["HTTP_HOST"] . '/' . $path);
}
示例7: save
public static function save($typeModel, $idModel, $files_field_name = 'upload', $need_file_name = '')
{
$Upload = CUploadedFile::getInstanceByName($files_field_name);
if (is_null($Upload)) {
return false;
}
$folder = self::makePath($typeModel, $idModel);
if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
if ($need_file_name == '') {
$newName = str_replace('.' . $Upload->getExtensionName(), '', urlencode($Upload->getName())) . "-" . date("YmdHis", time()) . '.' . $Upload->getExtensionName();
} else {
//добавка для сохранения кадров под конкретным именем
$newName = $need_file_name;
}
$newPath = $folder . self::DS . $newName;
if ($Upload->saveAs($newPath)) {
if (file_exists($newPath)) {
return $newName;
} else {
return false;
}
} else {
return false;
}
}
示例8: actionCreate
public function actionCreate()
{
$id = intval($_GET['id']);
if (!$id) {
exit('error 1');
}
$dir = Yii::app()->params['uploadPathImage'] . 'gallery/' . $id;
$upload = CUploadedFile::getInstanceByName('Filedata');
if ($upload->getSize()) {
$model = new GalleryImage();
$model->gallery_id = $id;
$model->save();
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$bigFile = $dir . '/' . $model->id . '_origin.' . $upload->getExtensionName();
$smallFile = $dir . '/' . $model->id . '.' . $upload->getExtensionName();
$upload->saveAs($bigFile);
// 压缩文件
$image = Yii::app()->image->load($bigFile);
$image->resize(Yii::app()->params['uploadMaxWidth'], Yii::app()->params['uploadMaxHeight'])->quality(Yii::app()->params['uploadQuality']);
$image->save($smallFile);
$model->file = $id . '/' . $model->id . '.' . $upload->getExtensionName();
$model->save();
echo json_encode(['id' => $model->id, 'file' => $model->file]);
} else {
exit('error 2');
}
}
示例9: actionImport
public function actionImport()
{
if (isset($_POST['importnow']) || isset($_FILES['importfile'])) {
$this->hasErrors = false;
$this->errors = array(array());
$filePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . '../../../../assets/upload.sql';
if (file_exists($filePath)) {
unlink($filePath);
}
if ($_FILES['importfile']['error'] != 0) {
$this->hasErrors = true;
if ($_FILES['importfile']['error'] == 4) {
$this->errors = array(array(Yii::t('lazy8', 'Returned error = 4 which means no file given'), Yii::t('lazy8', 'Select a file and try again')));
} else {
$this->errors = array(array(Yii::t('lazy8', 'Returned error') . ' = ' . $_FILES['importfile']['error'], Yii::t('lazy8', 'Select a file and try again')));
}
} else {
$importFile = CUploadedFile::getInstanceByName('importfile');
$importFile->saveAs($filePath);
$this->importTemplates($filePath);
}
} else {
if (isset($_GET['importing'])) {
$this->hasErrors = true;
$this->errors = array(array(Yii::t('lazy8', 'Upload failed. Possibly the file was too big.'), Yii::t('lazy8', 'Select a file and try again')));
} else {
$this->hasErrors = false;
$this->errors = array(array());
}
}
$this->render('showimport');
}
示例10: actionuploadDocuments
public function actionuploadDocuments()
{
if (!empty(Yii::app()->user->_data)) {
$userId = Yii::app()->user->_data->id;
}
// getting project Id
$projectId = Yii::app()->request->getPost('project_id');
if (isset($_POST['YumUserdocuments']) && isset($_POST['YumUserdocuments']['name'])) {
$model = new YumUserdocuments();
$model->attributes = $_POST['YumUserdocuments'];
$model->name = CUploadedFile::getInstanceByName('YumUserdocuments[name]');
if ($model->name instanceof CUploadedFile) {
// $userId =5;
// Prepend the id of the user to avoid filename conflicts
$fileName = $_FILES['YumUserdocuments']['name']['name'];
$filePath = Yum::module('userdocuments')->documentPath . '/' . $userId . '_' . $_FILES['YumUserdocuments']['name']['name'];
$model->name->saveAs($filePath);
$attrArr = array('name' => $fileName, 'path' => $filePath, 'created_by' => $userId);
$model->attributes = $attrArr;
if ($model->save(false)) {
if ($projectId) {
$userProjectDocuments = new YumUserdocumentsprojects();
$attrArrProject = array('project_id' => $projectId, 'userdocuments_id' => $model['userdocuments_id'], 'created_by' => $userId);
$userProjectDocuments->attributes = $attrArrProject;
if ($userProjectDocuments->save()) {
Yum::setFlash(Yum::t('The Document was uploaded successfully'));
$this->redirect(array('//userproject/userproject/projectdetails?project_id=' . $projectId));
}
}
Yum::setFlash(Yum::t('The Document was uploaded successfully'));
$this->redirect(array('//userdocuments/userdocuments/index'));
}
}
}
}
示例11: actionImage
public function actionImage()
{
$params = Yii::app()->params;
$file = CUploadedFile::getInstanceByName('imgFile');
if ($file === null || $file->getHasError()) {
$this->jsonReturn($file === null ? 1 : $file->getError(), '上传失败,请联系管理员');
}
$imagesize = getimagesize($file->getTempName());
if ($imagesize === false) {
$this->jsonReturn(1, '请上传正确格式的图片');
}
$basePath = $params->staticPath;
$extension = image_type_to_extension($imagesize[2]);
$md5 = md5(file_get_contents($file->getTempName()));
$filename = $md5 . $extension;
$dirname = 'upload/' . $md5[0] . '/';
$fullPath = $params->staticPath . $dirname . $filename;
$fullDir = dirname($fullPath);
if (!is_dir($fullDir)) {
mkdir($fullDir, 0755, true);
}
if (file_exists($fullPath) || $file->saveAs($fullPath)) {
$url = $params->staticUrlPrefix . $dirname . $filename;
$this->jsonReturn(0, '', $url);
} else {
$this->jsonReturn(1, '上传失败,请联系管理员');
}
}
示例12: actionUpload
public function actionUpload($obj = null)
{
if (Yii::app()->user->isGuest) {
$this->redirect('/');
}
if (!$obj) {
$obj = 'default';
}
if ($_FILES['uploadFile']) {
$fileExt = array('doc', 'docx', 'xls', 'xlsx', 'txt', 'mp3');
$imageExt = array('jpg', 'gif', 'png', 'jpeg');
$serverPath = dirname(Yii::app()->request->scriptFile);
$folder = '/userdata/uploads/u' . Yii::app()->user->id . '/';
$file = CUploadedFile::getInstanceByName('uploadFile');
$fileName = time() . '.' . $file->getExtensionName();
if (in_array(strtolower($file->getExtensionName()), $fileExt) || in_array(strtolower($file->getExtensionName()), $imageExt)) {
if (in_array(strtolower($file->getExtensionName()), $imageExt)) {
UploadImages::upload($file->getTempName(), $fileName, $serverPath . $folder, 'tinymce', $obj . '_text_image');
} else {
if (!is_dir(Yii::getPathOfAlias('webroot') . $folder)) {
mkdir(Yii::getPathOfAlias('webroot') . $folder, 0777, true);
}
$file->saveAs(Yii::getPathOfAlias('webroot') . $folder . $fileName);
}
header("Content-type: application/xml; charset=utf-8");
exit('<?xml version="1.0" encoding="utf8"?><result>' . $folder . 'resize/' . $fileName . '</result>');
} else {
exit('Запрещенный формат файла');
}
} else {
exit('No file');
}
}
示例13: getByNameAndCatchError
/**
* Get an instance of CuploadedFile. Catches errors and throws a BadFileUploadException
* @var string $filesVariableName
*/
public static function getByNameAndCatchError($filesVariableName)
{
assert('is_string($filesVariableName)');
$uploadedFile = CUploadedFile::getInstanceByName($filesVariableName);
if ($uploadedFile == null) {
throw new FailedFileUploadException(Zurmo::t('Core', 'The file did not exist'));
} elseif ($uploadedFile->getHasError()) {
$error = $uploadedFile->getError();
$messageParams = array('{file}' => $uploadedFile->getName(), '{limit}' => self::getSizeLimit());
if ($error == UPLOAD_ERR_NO_FILE) {
$message = Zurmo::t('Core', 'The file did not exist');
} elseif ($error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE) {
$message = Zurmo::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.', $messageParams);
} elseif ($error == UPLOAD_ERR_PARTIAL) {
$message = Zurmo::t('yii', 'The file "{file}" is too large. Its size cannot exceed {limit} bytes.', $messageParams);
} elseif ($error == UPLOAD_ERR_NO_TMP_DIR) {
$message = Zurmo::t('yii', 'Missing the temporary folder to store the uploaded file "{file}".', $messageParams);
} elseif ($error == UPLOAD_ERR_CANT_WRITE) {
$message = Zurmo::t('yii', 'Failed to write the uploaded file "{file}" to disk.', $messageParams);
} elseif (defined('UPLOAD_ERR_EXTENSION') && $error == UPLOAD_ERR_EXTENSION) {
$message = Zurmo::t('yii', 'File upload was stopped by extension.');
} else {
//Unsupported or unknown error.
$message = Zurmo::t('Core', 'There was an error uploading the file.');
}
throw new FailedFileUploadException($message);
} else {
return $uploadedFile;
}
}
示例14: actionEditAvatar
public function actionEditAvatar()
{
$model = YumUser::model()->findByPk(Yii::app()->user->id);
if (isset($_POST['YumUser'])) {
$model->attributes = $_POST['YumUser'];
$model->setScenario('avatarUpload');
if (Yum::module('avatar')->avatarMaxWidth != 0) {
$model->setScenario('avatarSizeCheck');
}
$model->avatar = CUploadedFile::getInstanceByName('YumUser[avatar]');
if ($model->validate()) {
if ($model->avatar instanceof CUploadedFile) {
// Prepend the id of the user to avoid filename conflicts
$filename = Yum::module('avatar')->avatarPath . '/' . $model->id . '_' . $_FILES['YumUser']['name']['avatar'];
$model->avatar->saveAs($filename);
$model->avatar = $filename;
if ($model->save()) {
Yum::setFlash(Yum::t('The image was uploaded successfully'));
Yum::log(Yum::t('User {username} uploaded avatar image {filename}', array('{username}' => $model->username, '{filename}' => $model->avatar)));
$this->redirect(array('//profile/profile/view'));
}
}
}
}
$this->render('edit_avatar', array('model' => $model));
}
示例15: actionTambah
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'ubah' page.
*/
public function actionTambah()
{
$model = new UploadMonitorForm();
$monitor = new Monitor();
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['UploadMonitorForm'])) {
$scriptFile = CUploadedFile::getInstanceByName('UploadMonitorForm[nama_file]');
if (isset($scriptFile)) {
$ini_array = parse_ini_file($scriptFile->tempName, true);
// echo "Nama: {$ini_array['description']['name']} <br />";
// echo "Descripsi: {$ini_array['description']['description']} <br />";
// echo "Perintah: {$ini_array['config']['command']} <br />";
// echo "Output: {$ini_array['config']['output']} <br />";
// echo "View: {$ini_array['config']['view']}";
//$monitor = new Monitor;
$monitor->nama = $ini_array['description']['name'];
$monitor->deskripsi = $ini_array['description']['description'];
$monitor->perintah = $ini_array['config']['command'];
$monitor->output_type_id = OutputType::model()->find("nama = '{$ini_array['config']['output']}'")->id;
$monitor->view_type_id = isset($ini_array['config']['view']) ? ViewType::model()->find("nama = '{$ini_array['config']['view']}'")->id : NULL;
$monitor->prefix = isset($ini_array['config']['prefix']) ? $ini_array['config']['prefix'] : NULL;
$monitor->suffix = isset($ini_array['config']['suffix']) ? $ini_array['config']['suffix'] : NULL;
if ($monitor->save()) {
$this->redirect(array('ubah', 'id' => $monitor->id));
}
}
}
$this->render('tambah', array('model' => $model, 'monitor' => $monitor));
}