public function getImageOriginal() { if (file_exists($this->pathForIcons . "/apple-icon-original.png")) { $this->imageOriginal = UploadedFile::getInstance($model, 'imageOriginal'); } return $this->imageOriginal; }
public function actionUpload() { $model = new UploadForm(); if (Yii::$app->request->isPost) { $tanggal = date("YmdHis"); $model->file = UploadedFile::getInstance($model, 'file'); if ($model->file && $model->validate()) { $model->file->saveAs('uploads/data_prospek/' . $model->file->baseName . $tanggal . '.' . $model->file->extension); //$this->actionExupload(); } } return $this->render('upload', ['model' => $model]); }
public function actionCreate() { $model = new MeForm(); if ($model->load(Yii::$app->request->post())) { $model->file = UploadedFile::getInstance($model, 'file'); $photoName = 'uploads/' . $model->title . '.' . $model->file->extension; $model->file->saveAs($photoName); $model->photo = $photoName; $model->save(); return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } }
/** * @inheritdoc */ public function run() { $model = $this->model; if ($model->load($_POST)) { $file = UploadedFile::getInstance($model, 'file'); $model->fileName = $file->getBaseName() . '.' . $file->getExtension(); if ($model->validate()) { $uploaded = $file->saveAs(Yii::getAlias('@app/web/imgs') . "/{$model->path}"); } else { print_r($model->getErrors()); } } Yii::$app->response->format = Response::FORMAT_JSON; return ['files' => [['url' => "/imgs/{$model->path}", 'name' => 'name', 'type' => 'type', 'size' => 18932, 'deleteUrl' => 'url', 'deleteType' => 'DELETE']]]; }
public function saveUploadedFile($model, $attribute, $fileName = null, $obj = false, $returnObj = false) { $result = UploadedFile::getInstance($model, $attribute); if ($fileName == null) { $fileName = time() . '.' . $result->getExtension(); } if (strpos($fileName, "/") !== false) { $fileSubPath = substr($fileName, 0, strrpos($fileName, "/")); if (!is_dir($this->basePath . '/' . $fileSubPath)) { mkdir($this->basePath . '/' . $fileSubPath, $this->filePermission, true); } } if ($result->saveAs($this->basePath . "/" . $fileName)) { chmod($this->basePath . "/" . $fileName, $this->filePermission); } return $returnObj ? $returnObj : $fileName; }
function restoreAction() { $backupFile = new UploadedFile("backupFile"); if (!$backupFile->wasUploaded()) { return; } $gzipMode = $this->request->fileType == "gzip"; $fileName = $backupFile->getTempName(); $fp = $gzipMode ? gzopen($fileName, "r") : fopen($fileName, "r"); $inString = false; $query = ""; while (!feof($fp)) { $line = $gzipMode ? gzgets($fp) : fgets($fp); if (!$inString) { $isCommentLine = false; foreach (array("#", "--") as $commentTag) { if (strpos($line, $commentTag) === 0) { $isCommentLine = true; } } if ($isCommentLine || trim($line) == "") { continue; } } $deslashedLine = str_replace('\\', '', $line); if ((substr_count($deslashedLine, "'") - substr_count($deslashedLine, "\\'")) % 2) { $inString = !$inString; } $query .= $line; if (substr_compare(rtrim($line), ";", -1) == 0 && !$inString) { $this->database->sqlQuery($query); $query = ""; } } }
public function moveUploadedFile(UploadedFile $file, $uploadBasePath) { $originalName = $file->getOriginalName(); // use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test. $relativePath = date('Y-m', filemtime($this->file->getPath())); $targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName; $targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName; $ext = $this->file->getExtension(); $i = 1; while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) { if ($ext) { $prev = $i == 1 ? "" : $i; $targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath); } else { $targetFilePath = $targetFilePath . $i++; } } $targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath; if (!is_dir($targetDir)) { $ret = mkdir($targetDir, umask(), true); if (!$ret) { throw new \RuntimeException("Could not create target directory to move temporary file into."); } } $file->move($targetDir, basename($targetFilePath)); return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath); }
/** * Upload file to Amazon s3 * * @param UploadedFile $file * @param String $subdirectory * @param String $type * @return Array $uploadedFile */ private function s3Upload($file, $subdirectory, $type) { $client_original_name = $file->getClientOriginalName(); $fileName = time() . '_' . $client_original_name; $destinationPath = 'uploads/' . $subdirectory; $path = $destinationPath . '/' . $fileName; $image = Image::make($file->getRealPath()); switch ($type) { case 'profile_photo': $image->fit(128, 128, function ($constraint) { $constraint->upsize(); }); break; case 'profile_cover': $image->resize(1440, null, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); break; } $stream = $image->stream(); $s3 = Storage::disk('s3'); $s3->put($path, $stream->__toString(), 'public'); $client = $s3->getDriver()->getAdapter()->getClient(); $public_url = $client->getObjectUrl(env('S3_BUCKET'), $path); $original_name = pathinfo($client_original_name, PATHINFO_FILENAME); $uploadedFile = ['original_name' => $original_name, 'file_name' => $fileName, 'public_url' => $public_url, 'type' => $type]; return $uploadedFile; }
public function upload() { if (null === $this->file) { return; } $this->file->move($this->getUploadRootDir(), $this->path); unset($this->file); }
/** * @depends testConstructor * @param UploadedFile $uploadedFile * @return UploadedFile */ public function testMoveTo(UploadedFile $uploadedFile) { $tempName = uniqid('file-'); $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $tempName; $uploadedFile->moveTo($path); $this->assertFileExists($path); unlink($path); return $uploadedFile; }
public function Validate() { if ($this->file == null) { return; } $this->isValid = in_array($this->file->Extension(), $this->allowedTypes); if (!$this->IsValid()) { $this->AddMessage(Resources::GetInstance()->GetString('InvalidAttachmentExtension', array(implode(',', $this->allowedTypes)))); } }
public function Validate() { if ($this->file == null) { return; } $this->isValid = !$this->file->IsError(); if (!$this->IsValid()) { Log::Debug('Uploaded file %s is not valid. %s', $this->file->OriginalName(), $this->file->Error()); $this->AddMessage($this->file->Error()); } }
protected function saveFile(UploadedFile $file) { $upload_dir = public_path('uploads/'); $file_name = 'file-' . date('dmY-His') . '.' . $file->getClientOriginalExtension(); try { if ($file->move($upload_dir, $file_name)) { return $file_name; } else { return false; } } catch (\Exception $ex) { return abort(500, $ex->getMessage()); } }
/** * Handles the uploading and db entry for a file * * @param UploadedFile $file * @return array */ function upload_file($file) { global $db; // Handle file errors if ($file->error) { throw new UploadException($file->error); } // Check if a file with the same hash and size (a file which is the same) does already exist in // the database; if it does, delete the file just uploaded and return the proper link and data. $q = $db->prepare('SELECT filename, COUNT(*) AS count FROM files WHERE hash = (:hash) ' . 'AND size = (:size)'); $q->bindValue(':hash', $file->get_sha1(), PDO::PARAM_STR); $q->bindValue(':size', $file->size, PDO::PARAM_INT); $q->execute(); $result = $q->fetch(); if ($result['count'] > 0) { unlink($file->tempfile); return array('hash' => $file->get_sha1(), 'name' => $file->name, 'url' => POMF_URL . $result['filename'], 'size' => $file->size); } // Generate a name for the file $newname = generate_name($file); // Attempt to move it to the static directory if (move_uploaded_file($file->tempfile, POMF_FILES_ROOT . $newname)) { // Need to change permissions for the new file to make it world readable if (chmod(POMF_FILES_ROOT . $newname, 0644)) { // Add it to the database if (empty($_SESSION['id'])) { // Query if user is NOT logged in $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ' . 'expire, delid) VALUES (:hash, :orig, :name, :size, :date, ' . ':exp, :del)'); } else { // Query if user is logged in (insert user id together with other data) $q = $db->prepare('INSERT INTO files (hash, originalname, filename, size, date, ' . 'expire, delid, user) VALUES (:hash, :orig, :name, :size, ' . ':date, :expires, :delid, :user)'); $q->bindValue(':user', $_SESSION['id'], PDO::PARAM_INT); } // Common parameters binding $q->bindValue(':hash', $file->get_sha1(), PDO::PARAM_STR); $q->bindValue(':orig', strip_tags($file->name), PDO::PARAM_STR); $q->bindValue(':name', $newname, PDO::PARAM_STR); $q->bindValue(':size', $file->size, PDO::PARAM_INT); $q->bindValue(':date', date('Y-m-d'), PDO::PARAM_STR); $q->bindValue(':exp', null, PDO::PARAM_STR); $q->bindValue(':del', sha1($file->tempfile), PDO::PARAM_STR); $q->execute(); return array('hash' => $file->get_sha1(), 'name' => $file->name, 'url' => POMF_URL . $newname, 'size' => $file->size); } else { throw new Exception('Failed to change file permissions', 500); } } else { throw new Exception('Failed to move file to destination', 500); } }
protected function beforeInit() { $this->data = $this->request->getArray(array("subject", "text", "mailsPerMinute", "newsletterType", 'fromEmail')); $message = $this->customMessage->findByPk("newsletterFooter"); $this->data['newsletterFooterDescription'] = $message->description; if ($this->data['newsletterType'] == 'csv') { $csvFile = new UploadedFile('csvFile'); if ($csvFile->wasUploaded()) { $this->data['emails'] = array_values(file($csvFile->getTempName(), FILE_IGNORE_NEW_LINES)); } else { $this->data['emails'] = array(); } } }
public static function realImgSrc($imgSrc, $type = "main", $size = "normal", $title = '') { if ($imgSrc) { $path = "/uploads/images_thumbs/" . UploadedFile::fileNameToPath($imgSrc); } else { $imgSrc = "DefaultMainPhoto.jpg"; $path = "/templates/arfooo/images/"; } switch ($size) { case "small": $imgSrc = "s" . $imgSrc; break; case "medium": $imgSrc = "m" . $imgSrc; break; case "nano": $imgSrc = "n" . $imgSrc; break; } if ($title) { $path .= NameTool::strToAscii($title) . '-'; } $imgSrc = $path . $imgSrc; return AppRouter::getResourceUrl($imgSrc); }
public function upload() { if ($this->validate()) { if (isset($this->avatarFile)) { if (!is_dir(Yii::$app->params['uploadPath'] . '/avatar')) { mkdir(Yii::$app->params['uploadPath'] . '/avatar', 0777, true); } $this->avatarFile->saveAs(Yii::$app->params['uploadPath'] . '/avatar/' . $this->avatarFile->baseName . '.' . $this->avatarFile->extension); $this->avatar = '/avatar/' . $this->avatarFile->baseName . '.' . $this->avatarFile->extension; $this->save(false); } return true; } else { return false; } }
/** * Instantiate request from php _SERVER variable * @param array server */ public static function createFromGlobals() { $server = $_SERVER; $uriParts = parse_url($server['REQUEST_URI']); $uriParts['host'] = $server['SERVER_NAME']; $uriParts['port'] = $server['SERVER_PORT']; $uriParts['scheme'] = isset($server['REQUEST_SCHEME']) ? $server['REQUEST_SCHEME'] : (isset($server['HTTPS']) && $server['HTTPS'] == 'on' ? 'https' : 'http'); if (function_exists('getallheaders')) { // a correct case already $apacheHeaders = getallheaders(); foreach ($apacheHeaders as $header => $value) { $headers[$header] = array_map('trim', explode(',', $value)); } } else { $headers = array(); // normalize the header key foreach ($server as $key => $value) { if (substr($key, 0, 5) != 'HTTP_') { continue; } $name = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5))))); $headers[$name] = array_map('trim', explode(',', $value)); } } $request = new static($server['REQUEST_METHOD'], new Uri($uriParts), $headers, Stream::createFromContents(file_get_contents('php://input')), $server, $_COOKIE, UploadedFile::createFromGlobals($_FILES)); if ($server['REQUEST_METHOD'] == 'POST' && in_array($request->getMediaType(), array('application/x-www-form-urlencoded', 'multipart/form-data'))) { $request->setParsedBody($_POST); } return $request; }
/** * Action to upload a file to an asset * @return void Request ends */ public function actionUpload() { $input = craft()->request->getPost(); $file = UploadedFile::getInstanceByName('file'); $folder = craft()->assets->findFolder(array('sourceId' => $input['sourceId'])); craft()->assets->insertFileByLocalPath($file->getTempName(), $file->getName(), $folder->id, AssetConflictResolution::KeepBoth); // DropzonePlugin::log($file->getName(), LogLevel::Info); craft()->end(); }
/** * Initially processes $_FILES superglobal for easier use. * Only for internal usage. */ protected static function prefetchFiles() { self::$_files = array(); if (!isset($_FILES) || !is_array($_FILES)) { return; } foreach ($_FILES as $class => $info) { self::collectFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']); } }
function deleteSitePhotoFiles($src) { if (empty($src)) { return; } $dirPath = Config::get("SITES_THUMBS_PATH") . UploadedFile::fileNameToPath($src); $this->deleteFileIfExists($dirPath . "s" . $src); $this->deleteFileIfExists($dirPath . "m" . $src); $this->deleteFileIfExists($dirPath . "n" . $src); $this->deleteFileIfExists($dirPath . $src); }
/** * Retrieve instances of UploadedFile for specified fields */ public function getFiles($fieldNames) { $uploadedFiles = array(); foreach ($fieldNames as $field) { $file = UploadedFile::getInstanceByName($field); if ($file !== null) { $uploadedFiles[$field] = $file; } } return $uploadedFiles; }
/** * ConvertedFile constructor * @param UploadedFile $uploadedFile * @param int $index * @param array $file */ function __construct($uploadedFile, $index, $file) { if (empty($uploadedFile)) { throw new Exception('$uploadedFile parameter can not be empty'); } if (empty($file)) { throw new Exception('$file parameter can not be empty'); } $this->_convertedFileIndex = $index; $this->_uploadedFile = $uploadedFile; $this->_uploadedFileIndex = $uploadedFile->getIndex(); $this->_file = $file; $expectedSize = $this->_uploadedFile->getPackage()->getPackageField(sprintf(PostFields::fileSize, $this->_convertedFileIndex, $this->_uploadedFileIndex)); if ($expectedSize < 2 * 1024 * 1024 * 1024) { $actualSize = $this->_file['size']; if ($expectedSize != $actualSize) { throw new Exception('File is corrupted'); } } $this->_size = intval($expectedSize, 10); }
public static function getUploadedFilesFromPhp(array $phpFiles) { $files = array(); foreach ($phpFiles as $name => $phpFile) { // TODO <input type="file" name="files[]" /> $file = UploadedFile::createFromPhpUpload($phpFile); if ($file) { $files[$name] = $file; } } return $files; }
/** * @ORM\PostPersist() * @ORM\PostUpdate() */ public function upload() { if (null === $this->file) { return; } // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error // moving file into /data $this->file->move($this->getUploadRootDir(), $this->path); // creating symlink to acces file from web/... symlink($this->getUploadRootDir() . '/' . $this->path, $this->getWebPath()); unset($this->file); }
public function actionForm() { $form = new FullForm(); if (Yii::app()->request->getParam('FullForm')) { $form->attributes = Yii::app()->request->getParam('FullForm'); $form->fileField = UploadedFile::getInstanceByName("FullForm[fileField]"); if ($form->validate()) { $uploaded = $form->fileField->saveAs(dirname(__FILE__) . '/../files/tmp.txt'); $this->render('formSubmit', array('form' => $form, 'uploadedFileSaved' => $uploaded)); Yii::app()->end(); } } $this->render('form', array('model' => $form)); }
/** * @inheritDoc IFieldType::prepValueFromPost() * * @param mixed $value * * @return mixed */ public function prepValueFromPost($value) { // See if we have uploaded file(s). $contentPostLocation = $this->getContentPostLocation(); if ($contentPostLocation) { $uploadedFiles = UploadedFile::getInstancesByName($contentPostLocation); if (!empty($uploadedFiles)) { // See if we have to validate against fileKinds $settings = $this->getSettings(); if (isset($settings->restrictFiles) && !empty($settings->restrictFiles) && !empty($settings->allowedKinds)) { $allowedExtensions = static::_getAllowedExtensions($settings->allowedKinds); $failedFiles = array(); foreach ($uploadedFiles as $uploadedFile) { $extension = mb_strtolower(IOHelper::getExtension($uploadedFile->getName())); if (!in_array($extension, $allowedExtensions)) { $failedFiles[] = $uploadedFile; } } // If any files failed the validation, make a note of it. if (!empty($failedFiles)) { $this->_failedFiles = $failedFiles; return true; } } // If we got here either there are no restrictions or all files are valid so let's turn them into Assets $fileIds = array(); $targetFolderId = $this->_determineUploadFolderId($settings); if (!empty($targetFolderId)) { foreach ($uploadedFiles as $file) { $tempPath = AssetsHelper::getTempFilePath($file->getName()); move_uploaded_file($file->getTempName(), $tempPath); $response = craft()->assets->insertFileByLocalPath($tempPath, $file->getName(), $targetFolderId); $fileIds[] = $response->getDataItem('fileId'); IOHelper::deleteFile($tempPath, true); } if (is_array($value) && is_array($fileIds)) { $fileIds = array_merge($value, $fileIds); } // Make it look like the actual POST data contained these file IDs as well, // so they make it into entry draft/version data $this->element->setRawPostContent($this->model->handle, $fileIds); return $fileIds; } } } return parent::prepValueFromPost($value); }
/** * Upload a logo for the admin panel. * * @return null */ public function actionUploadSiteImage() { $this->requireAjaxRequest(); $this->requireAdmin(); $type = craft()->request->getRequiredPost('type'); if (!in_array($type, $this->_allowedTypes)) { $this->returnErrorJson(Craft::t('That is not an accepted site image type.')); } // Upload the file and drop it in the temporary folder $file = UploadedFile::getInstanceByName('image-upload'); try { // Make sure a file was uploaded if ($file) { $fileName = AssetsHelper::cleanAssetName($file->getName()); if (!ImageHelper::isImageManipulatable($file->getExtensionName())) { throw new Exception(Craft::t('The uploaded file is not an image.')); } $folderPath = craft()->path->getTempUploadsPath(); IOHelper::ensureFolderExists($folderPath); IOHelper::clearFolder($folderPath, true); move_uploaded_file($file->getTempName(), $folderPath . $fileName); // Test if we will be able to perform image actions on this image if (!craft()->images->checkMemoryForImage($folderPath . $fileName)) { IOHelper::deleteFile($folderPath . $fileName); $this->returnErrorJson(Craft::t('The uploaded image is too large')); } list($width, $height) = ImageHelper::getImageSize($folderPath . $fileName); if (IOHelper::getExtension($fileName) != 'svg') { craft()->images->cleanImage($folderPath . $fileName); } else { craft()->images->loadImage($folderPath . $fileName)->saveAs($folderPath . $fileName); } $constraint = 500; // If the file is in the format badscript.php.gif perhaps. if ($width && $height) { // Never scale up the images, so make the scaling factor always <= 1 $factor = min($constraint / $width, $constraint / $height, 1); $html = craft()->templates->render('_components/tools/cropper_modal', array('imageUrl' => UrlHelper::getResourceUrl('tempuploads/' . $fileName), 'width' => round($width * $factor), 'height' => round($height * $factor), 'factor' => $factor, 'constraint' => $constraint, 'fileName' => $fileName)); $this->returnJson(array('html' => $html)); } } } catch (Exception $exception) { $this->returnErrorJson($exception->getMessage()); } $this->returnErrorJson(Craft::t('There was an error uploading your photo')); }
public function upload() { $this->setScenario('upload'); if ($this->validate()) { $patch = Yii::getAlias('@uploads/' . $this->dirName); if (!is_dir($patch)) { mkdir($patch); } $fileName = 'sl_' . Yii::$app->security->generateRandomString(8) . '.' . $this->imageFile->extension; if ($this->imageFile->saveAs($patch . '/' . $fileName)) { $this->removeImage(); } $this->image = $fileName; return true; } return false; }
public function actionImageUpload() { $imageFile = UploadedFile::getInstanceByName('Transport[name]'); $directory = \Yii::getAlias('@frontend/web/img/temp') . DIRECTORY_SEPARATOR . Yii::$app->session->id . DIRECTORY_SEPARATOR; if (!is_dir($directory)) { mkdir($directory); } if ($imageFile) { $uid = uniqid(time(), true); $fileName = $uid . '.' . $imageFile->extension; $filePath = $directory . $fileName; if ($imageFile->saveAs($filePath)) { $path = '/img/temp/' . Yii::$app->session->id . DIRECTORY_SEPARATOR . $fileName; return Json::encode(['files' => [['name' => $fileName, 'size' => $imageFile->size, "url" => $path, "thumbnailUrl" => $path, "deleteUrl" => 'image-delete?name=' . $fileName, "deleteType" => "POST"]]]); } } return ''; }