public function save() { if (isset($this->reading) and $this->reading != '') { $savemodel = new Calibration(); $savemodel->measure = 'mm'; $savemodel->height = $this->reading; $savemodel->sensorid = $this->sensorid; $savemodel->datetime = $this->date; $savemodel->youremail = $this->youremail; $savemodel->yourname = $this->yourname; $result = $savemodel->save(); $this->id = $savemodel->sensorid; return $result; } else { $savemodel = new File(); $savemodel->sensorid = $this->sensorid; $savemodel->startdate = $this->date; $savemodel->enddate = $this->date; $savemodel->status = 'processed'; $this->file = UploadedFile::getInstance($this, 'file'); $savemodel->extension = end(explode(".", $this->file->name)); $result = $savemodel->save(); // save to get the ID $savemodel->filename = $savemodel->id . "_" . $this->file->name; $path = Yii::getAlias('@app') . Yii::$app->params['uploadPath'] . $savemodel->filename; if ($result) { $this->file->saveAs($path); } $result = $savemodel->save(); $this->id = $savemodel->sensorid; return $result; } }
/** * Creates a new File model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new File(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $dir = Yii::getAlias('@app/uf'); foreach (UploadedFile::getInstances($model, 'files') as $file) { $file->saveAs($dir . '/' . $file->baseName . '.' . $file->extension); $new_file = new File(); $new_file->setAttributes($model->attributes); $new_file->file_name = $file->baseName . '.' . $file->extension; $new_file->file_path = $dir . '/' . $file->baseName . '.' . $file->extension; $new_file->table_name = 'person'; $new_file->class_name = Person::className(); $new_file->save(); } Yii::$app->getSession()->addFlash('success', "Запись \"{$model->id}\" успешно добавлена."); return $this->redirect(Url::previous() != Yii::$app->homeUrl ? Url::previous() : ['view', 'id' => $model->id]); } else { if (Yii::$app->request->referrer != Yii::$app->request->absoluteUrl) { Url::remember(Yii::$app->request->referrer ? Yii::$app->request->referrer : null); } if (!Yii::$app->request->isPost) { $model->setAttributes(Yii::$app->request->get()); } return $this->render('create', ['model' => $model]); } }
/** * Saves file to a random folder * @param \stdClass $fileData, example: * object(stdClass)[82] * public 'name' => string 'SampleVideo_1080x720_20mb (1).mp4' (length=33) * public 'size' => int 21069678 * public 'type' => string 'video/mp4' (length=9) * public 'extension' => string 'mp4' (length=3) * * @return int File record id * @author Alex Makhorin */ public function saveFileToStorage($fileData) { $tmpFilePath = $this->tmpDirectory . $fileData->name; $randomDir = $this->generateRandomDirectory($fileData->name); $randomName = $this->generateRandomName(); $newPath = $this->storageDirectory . $randomDir . '/' . $randomName . '.' . $fileData->extension; $this->createFolders($newPath); rename($tmpFilePath, $newPath); $url = $this->storageUrl . $randomDir . '/' . $randomName . '.' . $fileData->extension; if (strpos($fileData->type, 'video/') === 0) { $type = FileType::TYPE_VIDEO; } elseif (strpos($fileData->type, 'image/') === 0) { $type = FileType::TYPE_IMAGE; } else { is_file($newPath) && unlink($newPath); throw new HttpException(400, 'No data to handle'); } $file = new File(); $file->file_type = $type; $file->mime_type = $fileData->type; $file->url = $url; $isSaved = $file->save(); if (!$isSaved) { throw new HttpException(500, 'DB error occured: ' . \yii\helpers\VarDumper::dumpAsString($file->getErrors())); } return $file->primaryKey; }
public static function UploadFile($request) { $type = FileType::findOrFail($request->input('file_type_id')); $file = new File(); $filename = uniqid(); $newname = $request->input('newname'); if ($request->hasFile('file')) { if (isset($newname[0])) { $file->slug = str_replace(['/', '\\'], '', $newname); } else { $file->slug = $filename; } $file->filename = $filename; $file->file_ext = $request->file('file')->getClientOriginalExtension(); $file->path_to_file = 'uploads/files/'; if ($type->image) { $file->path_to_file = 'uploads/images/'; } $destinationPath = public_path($file->path_to_file); $request->file('file')->move($destinationPath, $filename . '.' . $file->file_ext); $file->path_to_file = '/' . $file->path_to_file; $file->file_type_id = $type->id; $file->fullname = $file->filename . '.' . $file->file_ext; $file->description = $request->input('description'); $file->alt_text = $request->input('alt_text'); $file->uploader = null; $file->path_to_file = $file->path_to_file . $file->fullname; $file->save(); return redirect()->action('FilesController@index'); } return back()->withErrors(['File not found. Please try again']); }
public static function create(array $data = array()) { $file = new File(); $file->fill($data); $file->save(); $element = new Element(); $element->fill($data); $file->content()->save($element); }
/** * Creates a new File model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new File(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } }
public function actionSave() { $item = new File(); $periodStart = date('Y-m-d', strtotime($this->app->request->post->periodStart)); $periodEnd = date('Y-m-d', strtotime($this->app->request->post->periodEnd)); $this->app->request->post->periodStart = $periodStart; $this->app->request->post->periodEnd = $periodEnd; $item->fill($this->app->request->post); $item->save(); $this->redirect('/sources/default/'); }
/** * Creates a new File model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new File(); try { if ($model->load($_POST) && $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]); }
protected function saveFile(UploadedFile $file) { $upload_dir = public_path('img/avatar'); $file_name = 'images-' . date('dmY-His') . '.' . $file->getClientOriginalExtension(); try { if ($file->move($upload_dir, $file_name)) { $file = new File(); $file->setAttribute('name', $file_name); $file->setAttribute('path', $upload_dir); $file->save(); return $file->id; } else { return null; } } catch (\Exception $ex) { return abort(500, $ex->getMessage()); } }
/** * Creates a new File model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { if (!Yii::$app->user->can("admin")) { throw new HttpException(403, 'You are not allowed to perform this action.'); } $model = new File(); if ($model->load(Yii::$app->request->post())) { if (!file_exists($model->filepath)) { $model->addError('filepath', "File does not exist, please provide a valid path."); return $this->render('create', ['model' => $model]); } $model->size_bytes = filesize($model->filepath); if ($model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', ['model' => $model]); } } else { return $this->render('create', ['model' => $model]); } }
public function upload() { if ($this->validate()) { foreach ($this->files as $file) { $model = new File(); $model->collection_id = $this->collection_id; $model->name = str_replace('.' . $file->extension, '', $file->name); $model->type = $file->type; $model->extension = $file->extension; $model->size = $file->size; if ($model->save()) { if (!is_dir($model->filePath)) { mkdir($model->filePath, 0777, true); } $file->saveAs($model->filePath . '/' . $model->fileName); } } return true; } else { return false; } }
public function uploadFile(Request $request) { $user = Auth::user(); $type = $request->type; $file = $request->file('file'); $ext = strtolower($file->getClientOriginalExtension()); $size = $file->getSize(); $validator = Validator::make(['file' => $file, 'extension' => $ext, 'size' => $size], ['file' => 'required', 'extension' => 'required|in:csv', 'size' => 'max:100000']); if ($validator->fails()) { //dd($validator->errors()); return Ajax::info('file format error'); } $destinationPath = Config::get('app.file_path') . '/' . date('Ym', time()); $save_path = public_path() . '/' . $destinationPath; $file_name = md5($file->getClientOriginalName() . time()) . '.' . $ext; if (!is_dir($save_path)) { mkdir($save_path, 755, true); } if ($file->move($save_path, $file_name)) { $url = url($destinationPath . '/' . $file_name); $file = new File(); $file->ext = $ext; $file->type = $type; $file->name = $file_name; $file->path = $destinationPath . '/' . $file_name; $file->uid = $user->id; $file->url = $url; $file->size = $size; $file->created_at = time(); $fid = $file->save(); if ($fid) { return AJAX::success($result = array('url' => $url, 'name' => $file_name)); } else { return AJAX::serverError(); } } else { return AJAX::info('upload file error'); } }
/** * Upload New File and attach it to a document * * @param Int $document * @param Request $request * @return Response */ public function postFileToDocument($document, Request $request) { if (!$this->appKeyAvailable($request)) { return $this->notAuthorized($request); } $upload = array('file' => $request->file('file')); $rules = array('file' => 'required'); $validator = Validator::make($upload, $rules); if (!empty($document) && !$this->isDocument($document)) { $this->setResultError("Document not found", 404); } elseif ($validator->fails()) { $this->setResultError($validator->messages(), 400); } elseif (!$this->setSessionUser($request)) { $this->setResultError("Not logged in", 401); } elseif ($document !== null && Document::find($document)->user_id != $this->user->id && !$this->isModerator()) { $this->setResultError("Unauthorized action", 403); } else { if ($request->file('file')->isValid()) { $destinationPath = '../uploads'; $extension = Input::file('file')->getClientOriginalExtension(); $fileName = uniqid() . '.' . $extension; $file = new File(); $file->user_id = $this->user->id; $file->document_id = $document; $file->name = Input::file('file')->getClientOriginalName(); $file->mime = Input::file('file')->getMimeType(); $file->size = Input::file('file')->getSize(); $file->path = $destinationPath . '/' . $fileName; Input::file('file')->move($destinationPath, $fileName); $file->save(); $this->setAllowed(null, $file->id, $this->user->id, null, 'all'); $this->setResultOk(); $this->setFileData($file); } else { $this->setResultError('File is not valid', 400); } } return $this->setResponse(); }
function updateCover(array $params) { $response = new ResponseEntity(); try { $image = $params['image']; $user = User::find(Auth::user()->id); if ($image && $user) { $dataImageBase64Type = 'data:image/png;base64,'; $validImage = false; $test = strpos($image, $dataImageBase64Type); // png if ($test !== FALSE) { // yeah, its png $validImage = true; } else { $dataImageBase64Type = 'data:image/jpeg;base64,'; $test = strpos($image, $dataImageBase64Type); // jpeg if ($test !== FALSE) { // yeah, its jpeg $validImage = true; } } if ($validImage) { $img = str_replace($dataImageBase64Type, '', $image); $pos = strpos($image, ';'); $typeArr = explode(':', substr($image, 0, $pos)); if (is_array($typeArr) && count($typeArr) == 2) { $type = $typeArr[1]; $types = ['image/png' => '.png', 'image/jpeg' => '.jpg']; if (array_key_exists($type, $types)) { $data = base64_decode($img); $file = env('FILE_UPLOAD_PATH') . md5($img) . $types[$type]; $success = file_put_contents($file, $data); if ($success) { $f = new File(); $f->new_filename = md5($img) . $types[$type]; $f->mime_type = $type; if ($f->save()) { // delete previous cover photo $prevFile = File::find($user->cover_photo_file_id); if ($prevFile) { \File::delete(env('FILE_UPLOAD_PATH') . $prevFile->new_filename); $prevFile->delete(); } // save new cover photo $user->cover_photo_file_id = $f->id; $user->save(); $response->setSuccess(true); } } } } } } } catch (\Exception $e) { $response->setMessages([$e->getMessage()]); } return $response; }
/** * @param \App\Events\Files\Uploaded $event * * @return \Symfony\Component\HttpFoundation\JsonResponse */ public function handle(Uploaded $event) { $uploadUuid = $event->uploadUuid; $request = $event->request; /* |-------------------------------------------------- | Move file to its final permanent destination. |-------------------------------------------------- */ $hash = hash_file('sha256', app('filestream')->getAbsolutePath($uploadUuid)); $destination = $hash; if (config('filesystems.load_balancing.enabled')) { $config = config('filesystems.load_balancing'); $folders = []; for ($i = 0; $i < $config['depth']; $i++) { $folders[] = substr($hash, -1 * ($i + 1) * $config['length'], $config['length']); } $destination = implode(DIRECTORY_SEPARATOR, array_merge($folders, [$hash])); } $filesystem = app('filesystem')->disk(); !$filesystem->exists($destination) ? $filesystem->move($uploadUuid, $destination) : $filesystem->delete($uploadUuid); /* |--------------------------------- | Check the tag and its limit. |--------------------------------- */ /** @var \App\Models\User $me */ $me = app('sentinel')->getUser(); $tag = $request->get('qqtag'); $tagLimit = config('filesystems.allowed_tags_and_limits.' . $tag); if ($tagLimit > 0) { $allFilesWithSameTagBelongingToUser = $me->load(['files' => function (BelongsToMany $query) use($tag) { $query->wherePivot('tag', '=', $tag); }])->files; if (($numberOfFilesToDeleteToComplyWitTagLimit = $allFilesWithSameTagBelongingToUser->count() - $tagLimit + 1) > 0) { while ($numberOfFilesToDeleteToComplyWitTagLimit > 0) { $pivotToDelete = $allFilesWithSameTagBelongingToUser->shift(); app('filestream')->deleteFile($pivotToDelete->hash, $tag); $numberOfFilesToDeleteToComplyWitTagLimit--; } } } /* |------------------------------------ | Persist file record in database. |------------------------------------ */ $uploadedFile = new SymfonyFile(app('filestream')->getAbsolutePath($destination)); if (!($file = File::find($hash = $uploadedFile->getFilename()))) { $file = new File(); $file->hash = $hash; $file->disk = 'local'; $file->path = trim(str_replace(config('filesystems.disks.local.root'), '', $uploadedFile->getPathname()), DIRECTORY_SEPARATOR); $file->mime = $uploadedFile->getMimeType(); $file->size = $uploadedFile->getSize(); $file->save(); } $me->files()->newPivotStatement()->whereTag($tag)->whereFileHash($hash)->delete(); $file->uploaders()->attach([$me->getUserId() => ['uuid' => $request->get('qquuid'), 'original_client_name' => $request->get('qqfilename'), 'tag' => $tag]]); return response()->json(['success' => true, 'hash' => $file->hash])->setStatusCode(IlluminateResponse::HTTP_CREATED); }
return $file; }, 'updateFile' => function ($file) { if (is_array($this->galleryTitles)) { $file->title = ArrayHelper::getValue($this->galleryTitles, $file->id, $file->title); } return $file; }, 'extraFields' => function ($file, $fields) { $position = 0; if (is_array($this->galleryTitles)) { $position = array_search($file->id, array_keys($this->galleryTitles)); $position++; } return ['type' => 2, 'position' => $position]; }, 'relationQuery' => function ($query) { return $query->andWhere(['type' => 2]); }, 'rules' => ['imageSize' => ['minWidth' => 300, 'minHeight' => 300], 'mimeTypes' => ['image/png', 'image/jpg', 'image/jpeg'], 'extensions' => ['jpg', 'jpeg', 'png'], 'maxSize' => 1024 * 1024 * 1, 'maxFiles' => 10, 'tooBig' => Yii::t('app.validators', 'File size must not exceed') . ' 1Mb'], 'preset' => ['80x80' => function ($realPath, $publicPath, $thumbPath) { Image::make($realPath . $publicPath)->fit(80, 80)->save($realPath . $thumbPath, 100); }]], 'text' => ['storage' => 'localFs', 'baseUrl' => '@web/uploads', 'type' => 'image', 'relation' => 'files', 'templatePath' => function ($file) { $date = new \DateTime(is_object($file->date_create) ? null : $file->date_create); return '/' . $date->format('Ym') . '/' . $file->id . '/' . $file->name; }, 'createFile' => function ($path, $name) { $file = new File(); $file->title = $name; $file->generateName(pathinfo($name, PATHINFO_EXTENSION)); $file->save(); return $file; }, 'extraFields' => function () { return ['type' => 3]; }, 'relationQuery' => function ($query) { return $query->andWhere(['type' => 3]); }, 'rules' => ['mimeTypes' => ['image/png', 'image/jpg', 'image/jpeg'], 'extensions' => ['jpg', 'jpeg', 'png'], 'maxSize' => 1024 * 1024 * 1, 'tooBig' => Yii::t('app.validators', 'File size must not exceed') . ' 1Mb']]]];
private function handleAttachedImages($images, $announcementId) { $filePath = env('FILE_UPLOAD_PATH'); $limit = 5 * 1024 * 1024; // 5MB foreach ($images as $image) { if ($image->getClientSize() <= $limit) { $f = new File(); $f->original_filename = $image->getClientOriginalName(); $f->new_filename = md5($announcementId . $image->getClientOriginalName()) . '.' . $image->getClientOriginalExtension(); $f->mime_type = $image->getClientMimeType(); $f->save(); DB::table('announcement_files')->insert([['announcement_id' => $announcementId, 'file_id' => $f->id]]); // handle upload files try { $finalFn = MyHelper::getImageFromStorage($announcementId, $f->new_filename); $image->move($filePath, $finalFn); } catch (\Exception $x) { throw new \RuntimeException($x); } } } }
private function createThumbnail($file) { $response = false; $remove_from_temp = false; $path_info = pathinfo($file['file_name']); if (!in_array($path_info['extension'], ['zip', '7z', 'rar', 'pam', 'tgz', 'bz2', 'iso', 'ace'])) { $path = RESOURCES . DS . $file['file_path'] . DS . $file['file_name']; if (in_array($path_info['extension'], ['xlsx', 'xls', 'docx', 'doc', 'odt', 'ppt', 'pptx', 'pps', 'ppsx', 'txt', 'csv', 'log'])) { $command = env('LIBREOFFICE', 'soffice') . " --headless --convert-to pdf:writer_pdf_Export --outdir " . TEMP . " " . $path . " > /dev/null"; exec($command); $source = TEMP . DS . $path_info['filename'] . ".pdf[0]"; $remove_from_temp = TEMP . DS . $path_info['filename'] . ".pdf"; } elseif (in_array($path_info['extension'], ['mp4', 'mpg', 'avi', 'mkv', 'flv', 'xvid', 'divx', 'mpeg', 'mov', 'vid', 'vob'])) { $command = env('FFMPEG', 'ffmpeg') . " -i " . $path . " -ss 00:00:01.000 -vframes 1 " . TEMP . DS . $path_info['filename'] . ".png > /dev/null"; exec($command); $source = TEMP . DS . $path_info['filename'] . ".png"; $remove_from_temp = $source; } else { $path .= $path_info["extension"] == "pdf" ? "[0]" : ""; $source = $path; } $destination = THUMBNAILS . DS . $path_info['filename'] . ".png"; $command2 = env('CONVERT', 'convert') . " -resize '384x384' {$source} {$destination}"; $result = exec($command2); if (file_exists($destination)) { if (file_exists($destination)) { if ($remove_from_temp) { unlink($remove_from_temp); } } $thumbnail = new File(); $thumbnail->name = $file['name']; $thumbnail->file_path = 'thumbnails'; $thumbnail->file_name = pathinfo($file['file_name'])['filename'] . ".png"; $thumbnail->file_extension = 'png'; $thumbnail->resource_type = "Thumbnail"; $thumbnail->uploader_id = $file['uploader_id']; $created = $thumbnail->save(); if ($created) { $file->thumbnail_id = $thumbnail->id; $updated = $file->save(); if ($updated) { $response = $thumbnail; } } } } return $response; }