本文整理汇总了PHP中File::save方法的典型用法代码示例。如果您正苦于以下问题:PHP File::save方法的具体用法?PHP File::save怎么用?PHP File::save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类File
的用法示例。
在下文中一共展示了File::save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
/**
* @param string $destination where to save file
* @param string|ConfigInterface $config
* @param RequestInterface $request optional
* @return bool
*/
public static function save($destination, $config, RequestInterface $request = null)
{
if (!$config instanceof ConfigInterface) {
$config = new Config(array('tempDir' => $config));
}
$file = new File($config, $request);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if ($file->checkChunk()) {
header("HTTP/1.1 200 Ok");
} else {
header("HTTP/1.1 404 Not Found");
return false;
}
} else {
if ($file->validateChunk()) {
$file->saveChunk();
} else {
// error, invalid chunk upload request, retry
header("HTTP/1.1 400 Bad Request");
return false;
}
}
if ($file->validateFile() && $file->save($destination)) {
return true;
} else {
return false;
}
}
示例2: storeFileForIndexing
public function storeFileForIndexing($file_path)
{
$FileInstance = new File(array('init' => false));
if ($this->db) {
$FileInstance->setConnection($this->db);
}
$FileInstance->init();
$file_details = array('path' => $file_path, 'body' => file_get_contents($this->base_dir . DS . $file_path), 'hash' => md5_file($this->base_dir . DS . $file_path), 'has_been_analyzed' => false);
if ($SourceFile = $FileInstance->findFirstBy('path', $file_path)) {
if (!$file_details['has_been_analyzed']) {
$this->log('File ' . $file_details['path'] . ' is stored but not indexed.');
}
$file_details['has_been_analyzed'] = $SourceFile->hash == $file_details['hash'] && $SourceFile->get('has_been_analyzed');
if (!$file_details['has_been_analyzed']) {
$this->log('File ' . $file_details['path'] . ' marked for reanalizing');
$SourceFile->setAttributes($file_details);
$SourceFile->save();
} else {
$this->log('File ' . $file_details['path'] . ' is up to date');
}
} else {
$this->log('Storing file ' . $file_details['path']);
$SourceFile = new File(array('init' => false));
if ($this->db) {
$SourceFile->setConnection($this->db);
}
$SourceFile->init();
$SourceFile->setAttributes($file_details);
$SourceFile->save();
}
}
示例3: indexAction
public function indexAction()
{
$request = $this->getRequest();
if (!$request->isPost()) {
$this->getHelper('Redirector')->goto('index', 'index');
// action, controller
}
$c = Zend_Registry::get('config');
$apiKey = Zend_Filter::get($request->getPost('apikey'), 'Alnum');
try {
$user = User::findByApiKey($apiKey);
if ($user === null) {
$this->view->assign('response', 'Invalid API key.');
} else {
$user->setIp($request->getServer('REMOTE_ADDR'));
}
} catch (Zend_Db_Adapter_Exception $e) {
$this->view->assign('response', $e->getMessage());
}
if (isset($user)) {
if ($_FILES['file']['error'] === 0) {
$file = new File();
$file->setFileName($_FILES['file']['name']);
$file->setFileSize($_FILES['file']['size']);
$file->setTmpName($_FILES['file']['tmp_name']);
$file->setUploadedBy($user);
try {
$url = $file->save();
$this->view->assign('response', $url . "\n");
} catch (Exception $e) {
$this->view->assign('response', $e->getMessage());
}
} else {
switch ($_FILES['file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_INI_SIZE:
throw new Exception('The uploaded file exceeds the upload_max_filesize directive (' . ini_get('upload_max_filesize') . ') in php.ini.');
break;
case UPLOAD_ERR_FORM_SIZE:
throw new Exception('The uploaded file exceeds the MAX_FILE_SIZE directive' . 'that was specified in the HTML form.');
break;
case UPLOAD_ERR_PARTIAL:
throw new Exception('The uploaded file was only partially uploaded.');
break;
case UPLOAD_ERR_NO_FILE:
throw new Exception('No file was uploaded.');
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new Exception('Missing a temporary folder.');
break;
case UPLOAD_ERR_CANT_WRITE:
throw new Exception('Failed to write file to disk.');
break;
default:
throw new Exception('Unknown File Error.');
}
}
}
}
示例4: executePost
public function executePost(sfWebRequest $request)
{
$this->forward400If('' === (string) $request['body'], 'body parameter is not specified.');
$this->forward400If('' === (string) $request['toMember'], 'toMember parameter is not specified.');
$body = $request['body'];
$this->myMember = $this->member;
$toMember = Doctrine::getTable('Member')->find($request['toMember']);
$this->forward400Unless($toMember, 'invalid member');
$relation = Doctrine_Core::getTable('MemberRelationship')->retrieveByFromAndTo($toMember->getId(), $this->member->getId());
$this->forward400If($relation && $relation->getIsAccessBlock(), 'Cannot send the message.');
$message = Doctrine::getTable('SendMessageData')->sendMessage($toMember, SendMessageData::SMARTPHONE_SUBJECT, $body, array());
$file = $request->getFiles('message_image');
try {
$validator = new opValidatorImageFile(array('required' => false));
$clean = $validator->clean($file);
if (is_null($clean)) {
// if empty.
return sfView::SUCCESS;
}
} catch (Exception $e) {
$this->logMessage($e->getMessage());
$this->forward400('This image file is invalid.');
}
$file = new File();
$file->setFromValidatedFile($clean);
$file->save();
$messageFile = new MessageFile();
$messageFile->setMessageId($message->getId());
$messageFile->setFile($file);
$messageFile->save();
}
示例5: __construct
public function __construct()
{
$title = getInput("title");
$description = getInput("description");
// Create filestore object to store file information
$file = new File();
$file->title = $title;
$file->description = $description;
$file->owner_guid = getLoggedInUserGuid();
$file->access_id = "public";
$file->container_guid = getInput("container_guid");
$guid = $file->save();
uploadFile("file", $guid, getLoggedInUserGuid());
$file = getEntity($guid);
Image::createThumbnail($file->guid, TINY);
Image::createThumbnail($file->guid, SMALL);
Image::createThumbnail($file->guid, MEDIUM);
Image::createThumbnail($file->guid, LARGE);
Image::createThumbnail($file->guid, EXTRALARGE);
Image::createThumbnail($file->guid, HUGE);
new Activity(getLoggedInUserGuid(), "action:upload:file", $guid);
runHook("upload_file:redirect");
new SystemMessage("Your file has been uploaded.");
forward();
}
示例6: datos
function datos($campo_id, $etapa_id)
{
$etapa = Doctrine::getTable('Etapa')->find($etapa_id);
if (UsuarioSesion::usuario()->id != $etapa->usuario_id) {
echo 'Usuario no tiene permisos para subir archivos en esta etapa';
exit;
}
$campo = Doctrine_Query::create()->from('Campo c, c.Formulario.Pasos.Tarea.Etapas e')->where('c.id = ? AND e.id = ?', array($campo_id, $etapa_id))->fetchOne();
if (!$campo) {
echo 'Campo no existe';
exit;
}
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array('gif', 'jpg', 'png', 'pdf', 'doc', 'docx', 'zip', 'rar', 'ppt', 'pptx', 'xls', 'xlsx', 'mpp', 'vsd');
if (isset($campo->extra->filetypes)) {
$allowedExtensions = $campo->extra->filetypes;
}
// max file size in bytes
$sizeLimit = 20 * 1024 * 1024;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload('uploads/datos/');
if (isset($result['success'])) {
$file = new File();
$file->tramite_id = $etapa->Tramite->id;
$file->filename = $result['file_name'];
$file->tipo = 'dato';
$file->llave = strtolower(random_string('alnum', 12));
$file->save();
$result['id'] = $file->id;
$result['llave'] = $file->llave;
}
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
}
示例7: 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)));
}
}
示例8: export
public static function export(\Rebond\Core\ModelInterface $module)
{
$exportPath = \Rebond\Config::path('export');
$tempPath = \Rebond\Config::path('temp');
// TODO add XML model node
// generate data script
$dataScriptPath = $tempPath . 'data.sql';
$table = 'app_' . strtolower($module->getTitle());
$db = new Util\Data();
$result = $db->select('SELECT * FROM ' . $table);
$script = $db->backupData($table, $result);
$result = $db->select('SELECT * FROM cms_content WHERE module_id = ?', [$module->getId()]);
$script .= $db->backupData('cms_content', $result);
File::save($dataScriptPath, 'w', $script);
// create zip
$zipFile = $module->getTitle() . '.zip';
$zip = new \ZipArchive();
$res = $zip->open($exportPath . $zipFile, \ZIPARCHIVE::OVERWRITE);
if (!$res) {
return $res;
}
$modulePath = FULL_PATH . 'Rebond/App/' . $module->getTitle() . '/';
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($modulePath));
foreach ($iterator as $file) {
$filename = str_replace($modulePath, '', str_replace('\\', '/', $file));
if (file_exists($file) && substr($filename, -1) != '.') {
$zip->addFile($file, $filename);
}
}
$zip->addFile($dataScriptPath, 'data.sql');
$zip->close();
return $zipFile;
}
示例9: handleFileUpload
/**
* Handles a single upload by given CUploadedFile and returns an array
* of informations.
*
* The 'error' attribute of the array, indicates there was an error.
*
* Informations on error:
* - error: true
* - errorMessage: some message
* - name: name of the file
* - size: file size
*
* Informations on success:
* - error: false
* - name: name of the uploaded file
* - size: file size
* - guid: of the file
* - url: url to the file
* - thumbnailUrl: url to the thumbnail if exists
*
* @param type $cFile
* @return Array Informations about the uploaded file
*/
protected function handleFileUpload($cFile, $object = null)
{
$output = array();
$file = new File();
$file->setUploadedFile($cFile);
if ($object != null) {
$file->object_id = $object->getPrimaryKey();
$file->object_model = get_class($object);
}
if ($file->validate() && $file->save()) {
$output['error'] = false;
$output['guid'] = $file->guid;
$output['name'] = $file->file_name;
$output['title'] = $file->title;
$output['size'] = $file->size;
$output['mimeIcon'] = HHtml::getMimeIconClassByExtension($file->getExtension());
$output['mimeBaseType'] = $file->getMimeBaseType();
$output['mimeSubType'] = $file->getMimeSubType();
$output['url'] = $file->getUrl("", false);
$output['thumbnailUrl'] = $file->getPreviewImageUrl(200, 200);
} else {
$output['error'] = true;
$output['errors'] = $file->getErrors();
}
$output['name'] = $file->file_name;
$output['size'] = $file->size;
$output['deleteUrl'] = "";
$output['deleteType'] = "";
$output['thumbnailUrl'] = "";
return $output;
}
示例10: afterSave
public function afterSave($event)
{
if (!empty($_FILES)) {
$model = $this->getOwner();
$file = new File();
$file->filename = UploadUtils::createUniquefilename($_FILES[self::NAME]['name'], UploadUtils::getPath(self::$fileDir));
if (move_uploaded_file($_FILES[self::NAME]['tmp_name'], UploadUtils::getPath(self::$fileDir) . DIRECTORY_SEPARATOR . $file->filename)) {
$file->entity = get_class($model);
$file->EXid = $model->getPrimaryKey();
$file->uid = Yii::app()->user->id;
$file->tag = $this->tag;
$file->weight = 0;
$file->timestamp = time();
$file->filemime = CFileHelper::getMimeTypeByExtension($_FILES[self::NAME]['name']);
$file->filesize = $_FILES[self::NAME]['size'];
$file->status = File::STATUS_SAVED;
// Ensure all other files of the entity are deleted
//UploadUtils::deleteAllFiles(get_class($this->getOwner()), self::$fileDir);
if ($file->save()) {
Yii::trace("File saved " . $file . "!!!!");
} else {
Yii::log("Could not save File " . print_r($file->getErrors(), true), CLogger::LEVEL_ERROR);
}
} else {
Yii::log("Couldnt move the file", CLogger::LEVEL_ERROR);
}
} else {
Yii::log("Files empty!!!", CLogger::LEVEL_ERROR);
}
}
示例11: generar
public function generar($etapa_id) {
$etapa = Doctrine::getTable('Etapa')->find($etapa_id);
$filename_uniqid = uniqid();
//Generamos el file
$file = new File();
$file->tramite_id = $etapa->tramite_id;
$file->tipo = 'documento';
$file->llave = strtolower(random_string('alnum', 12));
$file->llave_copia = $this->tipo == 'certificado' ? strtolower(random_string('alnum', 12)) : null;
$file->llave_firma = strtolower(random_string('alnum', 12));
if($this->tipo=='certificado'){
$file->validez = $this->validez;
$file->validez_habiles= $this->validez_habiles;
}
$file->filename = $filename_uniqid . '.pdf';
$file->save();
//Renderizamos
$this->render($file->id, $file->llave_copia, $etapa->id, $file->filename, false);
$filename_copia = $filename_uniqid . '.copia.pdf';
$this->render($file->id, $file->llave_copia, $etapa->id,$filename_copia, true);
return $file;
}
示例12: share_validation
public function share_validation()
{
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_error_delimiters('<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">×</button>', '</div>');
//mise en place des regles
$this->form_validation->set_rules('keywords', 'Mots-clés', 'required|encode_php_tags|htmlspecialchars|trim|xss_clean|max_length[200]');
$this->form_validation->set_rules('description', 'Description', 'required|encode_php_tags|htmlspecialchars|trim|xss_clean|max_length[300]');
if ($this->form_validation->run() == FALSE) {
//on affiche le formulaire
$this->share();
} else {
// upload du fichier
$file_up = new Upload();
$user = unserialize($this->session->userdata('user_obj'));
if ($file_up->upload_file($user->id, array('userfile'))) {
// Création fichier
$file = new File();
$file->id_user = $user->id;
$file->desc = $this->input->post('description');
$file->keywords = $this->input->post('keywords');
$file->url = $file_up->files_uploaded[0][0];
$file->type = $file_up->files_uploaded[0][1];
//sauvegarde du fichier
$file->save();
//notification
$this->session->set_userdata('notif_ok', '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button><strong>Bravo! </strong> Votre partage a été réussi.</div>');
//redirection sur l'actualité
redirect('flux', 'refresh');
} else {
//on affiche le formulaire
$this->share();
}
}
}
示例13: save
public function save()
{
$file = new File();
$file->setFromValidatedFile($this->getValue('file'));
$file->setName(sprintf('admin_%s_%d', $this->getValue('imageName'), time()));
return $file->save();
}
示例14: add
/**
* Ajoute un log au fichier correspondant
*
* @param string $type -> Type de log : access, action, etc
* @param string $str -> Ligne de log à écrire
* @return bool
*/
public static function add($type, $str)
{
$out = false;
$type = strtolower($type);
if (defined('USER_PAGE')) {
$userPage = USER_PAGE;
} else {
$userPage = 'index';
}
if (defined('SERVER_NAME')) {
$serverName = '[' . utf8_decode(SERVER_NAME) . '] ';
} else {
$serverName = null;
}
$str = '[' . date('d/m/Y H:i:s') . '] [' . $_SERVER['REMOTE_ADDR'] . '] : ' . $serverName . '[' . $userPage . '] ' . utf8_decode($str) . "\n";
$path = self::$LOGS_PATH . $type . '.log';
if (file_exists($path)) {
if (File::save($path, utf8_encode($str)) !== true) {
$error = Utils::t('Unable to add log in file:') . ' ' . $type . '.';
if ($_SESSION['error'] != null) {
$_SESSION['error'] .= '<br />' . $error;
} else {
$_SESSION['error'] = $error;
}
} else {
$out = true;
}
}
return $out;
}
示例15: adminGateKeeper
function __construct()
{
adminGateKeeper();
$guid = getInput("guid");
$title = getInput("title");
$description = getInput('description');
$price = getInput("price");
$hidden = getInput("hidden") == 0 ? false : true;
$product = getEntity($guid);
$product->title = $title;
$product->description = $description;
$product->price = $price;
$product->hidden = $hidden;
$product->save();
$product->createAvatar();
if (isset($_FILES["download"]) && $_FILES["download"]["name"]) {
$file = new File();
$file->access_id = "product";
$file->container_guid = $product->guid;
$guid = $file->save();
uploadFile("download", $guid, array("zip"));
$product->download = $guid;
}
new SystemMessage("Your product has been updated.");
forward("store");
}