Skip to content

Commit

Permalink
Refactor FileController and File Model. Fix bug with src in editing f…
Browse files Browse the repository at this point in the history
…ile name
  • Loading branch information
mitrallex committed Jul 27, 2018
1 parent 2036cb0 commit 4739239
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 70 deletions.
87 changes: 86 additions & 1 deletion app/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,99 @@
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Auth;

class File extends Model
{

protected $fillable = [
'name', 'type', 'extension', 'user_id'
];

public static $image_ext = ['jpg', 'jpeg', 'png', 'gif'];
public static $audio_ext = ['mp3', 'ogg', 'mpga'];
public static $video_ext = ['mp4', 'mpeg'];
public static $document_ext = ['doc', 'docx', 'pdf', 'odt'];

/**
* Get maximum file size
* @return int maximum file size in kilobites
*/
public static function getMaxSize()
{
return (int)ini_get('upload_max_filesize') * 1000;
}

/**
* Get directory for the specific user
* @return string Specific user directory
*/
public function getUserDir()
{
return Auth::user()->name . '_' . Auth::id();
}

/**
* Get all extensions
* @return array Extensions of all file types
*/
public static function getAllExtensions()
{
$merged_arr = array_merge(self::$image_ext, self::$audio_ext, self::$video_ext, self::$document_ext);
return implode(',', $merged_arr);
}

/**
* Get type by extension
* @param string $ext Specific extension
* @return string Type
*/
public function getType($ext)
{
if (in_array($ext, self::$image_ext)) {
return 'image';
}

if (in_array($ext, self::$audio_ext)) {
return 'audio';
}

if (in_array($ext, self::$video_ext)) {
return 'video';
}

if (in_array($ext, self::$document_ext)) {
return 'document';
}
}

/**
* Get file name and path to the file
* @param string $type File type
* @param string $name File name
* @param string $extension File extension
* @return string File name with the path
*/
public function getName($type, $name, $extension)
{
return '/public/' . $this->getUserDir() . '/' . $type . '/' . $name . '.' . $extension;
}

/**
* Upload file to the server
* @param string $type File type
* @param object $file Uploaded file from request
* @param string $name File name
* @param string $extension File extension
* @return boolean True if file successfully uploaded, otherwise - false
*/
public function upload($type, $file, $name, $extension)
{
$path = '/public/' . $this->getUserDir() . '/' . $type . '/';
$full_name = $name . '.' . $extension;

return Storage::putFileAs($path, $file, $full_name);
}

public function user()
{
Expand Down
74 changes: 12 additions & 62 deletions app/Http/Controllers/FileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@

class FileController extends Controller
{
private $image_ext = ['jpg', 'jpeg', 'png', 'gif'];
private $audio_ext = ['mp3', 'ogg', 'mpga'];
private $video_ext = ['mp4', 'mpeg'];
private $document_ext = ['doc', 'docx', 'pdf', 'odt'];

/**
* Constructor
*/
Expand Down Expand Up @@ -65,25 +60,22 @@ public function index($type, $id = null)
*/
public function store(Request $request)
{
$max_size = (int)ini_get('upload_max_filesize') * 1000;
$all_ext = implode(',', $this->allExtensions());

$this->validate($request, [
'name' => 'required|unique:files',
'file' => 'required|file|mimes:' . $all_ext . '|max:' . $max_size
'file' => 'required|file|mimes:' . File::getAllExtensions() . '|max:' . File::getMaxSize()
]);

$model = new File();
$file = new File();

$file = $request->file('file');
$ext = $file->getClientOriginalExtension();
$type = $this->getType($ext);
$uploaded_file = $request->file('file');
$original_ext = $uploaded_file->getClientOriginalExtension();
$type = $file->getType($original_ext);

if (Storage::putFileAs('/public/' . $this->getUserDir() . '/' . $type . '/', $file, $request['name'] . '.' . $ext)) {
return $model::create([
if ($file->upload($type, $uploaded_file, $request['name'], $original_ext)) {
return $file::create([
'name' => $request['name'],
'type' => $type,
'extension' => $ext,
'extension' => $original_ext,
'user_id' => Auth::id()
]);
}
Expand All @@ -109,8 +101,8 @@ public function edit($id, Request $request)
'name' => 'required|unique:files'
]);

$old_filename = '/public/' . $this->getUserDir() . '/' . $file->type . '/' . $file->name . '.' . $file->extension;
$new_filename = '/public/' . $this->getUserDir() . '/' . $request['type'] . '/' . $request['name'] . '.' . $request['extension'];
$old_filename = $file->getName($file->type, $file->name, $file->extension);
$new_filename = $file->getName($request['type'], $request['name'], $request['extension']);

if (Storage::disk('local')->exists($old_filename)) {
if (Storage::disk('local')->move($old_filename, $new_filename)) {
Expand All @@ -132,55 +124,13 @@ public function destroy($id)
{
$file = File::findOrFail($id);

if (Storage::disk('local')->exists('/public/' . $this->getUserDir() . '/' . $file->type . '/' . $file->name . '.' . $file->extension)) {
if (Storage::disk('local')->delete('/public/' . $this->getUserDir() . '/' . $file->type . '/' . $file->name . '.' . $file->extension)) {
if (Storage::disk('local')->exists($file->getName($file->type, $file->name, $file->extension))) {
if (Storage::disk('local')->delete($file->getName($file->type, $file->name, $file->extension))) {
return response()->json($file->delete());
}
}

return response()->json(false);
}


/**
* Get type by extension
* @param string $ext Specific extension
* @return string Type
*/
private function getType($ext)
{
if (in_array($ext, $this->image_ext)) {
return 'image';
}

if (in_array($ext, $this->audio_ext)) {
return 'audio';
}

if (in_array($ext, $this->video_ext)) {
return 'video';
}

if (in_array($ext, $this->document_ext)) {
return 'document';
}
}

/**
* Get all extensions
* @return array Extensions of all file types
*/
private function allExtensions()
{
return array_merge($this->image_ext, $this->audio_ext, $this->video_ext, $this->document_ext);
}

/**
* Get directory for the specific user
* @return string Specific user directory
*/
private function getUserDir()
{
return Auth::user()->name . '_' . Auth::id();
}
}
2 changes: 1 addition & 1 deletion app/Http/Middleware/RedirectIfAuthenticated.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class RedirectIfAuthenticated
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
return redirect(route('home'));
}

return $next($request);
Expand Down
16 changes: 13 additions & 3 deletions resources/assets/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ const app = new Vue({

editingFile: {},
deletingFile: {},
savedFile: {
type: '',
name: '',
extension: ''
},

notification: false,
showConfirm: false,
Expand All @@ -76,6 +81,7 @@ const app = new Vue({
axios.get('files/' + type + '?page=' + page).then(result => {
this.loading = false;
this.files = result.data.data.data;
console.log(this.files);
this.pagination = result.data.pagination;
}).catch(error => {
console.log(error);
Expand Down Expand Up @@ -144,6 +150,9 @@ const app = new Vue({

editFile(file) {
this.editingFile = file;
this.savedFile.type = file.type;
this.savedFile.name = file.name;
this.savedFile.extension = file.extension;
},

endEditing(file) {
Expand All @@ -158,17 +167,18 @@ const app = new Vue({
.then(response => {
if (response.data === true) {
this.showNotification('Filename successfully changed!', true);

var src = document.querySelector('[alt="' + file.name +'"]').getAttribute("src");
document.querySelector('[alt="' + file.name +'"]').setAttribute('src', src);
}
this.fetchFile(this.activeTab, this.pagination.current_page);

})
.catch(error => {
console.log(error);
this.errors = error.response.data.errors;
this.showNotification(error.response.data.message, false);
this.fetchFile(this.activeTab, this.pagination.current_page);
});

this.fetchFile(this.activeTab, this.pagination.current_page);
},

showNotification(text, success) {
Expand Down
7 changes: 4 additions & 3 deletions resources/views/main.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,14 @@
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
</div>

<div class="column " :class="isVideo ? 'is-half' : 'is-one-fifth'" v-for="file in files" v-cloak>
<br>
<div class="column " :class="isVideo ? 'is-half' : 'is-one-fifth'" v-for="file in files" >
<div class="card " :class="file.type == 'image' ? 'is-image' : ''">
<div class="card-image">
<button class="delete delete-file" title="Delete" @click="prepareToDelete(file)"></button>
<figure class="image is-4by3" v-if="file.type == 'image'" @click="showModal(file)">
<img src="" :src="'{{ asset('storage/' . Auth::user()->name . '_' . Auth::id()) }}' + '/' + file.type + '/' + file.name + '.' + file.extension" :alt="file.name">
<img v-if="file === editingFile" src="" :src="'{{ asset('storage/' . Auth::user()->name . '_' . Auth::id()) }}' + '/' + savedFile.type + '/' + savedFile.name + '.' + savedFile.extension" :alt="file.name">
<img v-if="file !== editingFile" src="" :src="'{{ asset('storage/' . Auth::user()->name . '_' . Auth::id()) }}' + '/' + file.type + '/' + file.name + '.' + file.extension" :alt="file.name">
</figure>

<div v-if="file.type == 'audio'">
Expand Down

0 comments on commit 4739239

Please sign in to comment.