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