Vue event bus, uploading files handles from file service.

This commit is contained in:
krzysiej
2022-06-02 13:43:08 +02:00
parent 1a5445a84a
commit e5562cddb1
8 changed files with 69 additions and 52 deletions

View File

@@ -1,4 +1,4 @@
// mydropzone_controller.js // filedropzone_controller.js
import { Controller } from '@hotwired/stimulus'; import { Controller } from '@hotwired/stimulus';
import axios from 'axios'; import axios from 'axios';
@@ -19,13 +19,7 @@ export default class extends Controller {
_onConnect(event) { _onConnect(event) {
// The dropzone was just created // The dropzone was just created
// console.info(event);
console.info('onconnect'); console.info('onconnect');
//
// axios.get('/book/search/modyfikowany+węgiel').then(response => {
// console.info(response.data);
// });
} }
_onChange(event) { _onChange(event) {
@@ -36,14 +30,13 @@ export default class extends Controller {
'Content-Type': 'multipart/form-data' 'Content-Type': 'multipart/form-data'
} }
}).then(() => { }).then(() => {
event.target.querySelector('.dropzone-preview-button').click() event.target.querySelector('.dropzone-preview-button').click();
window.EventBus.$emit('fileUploaded');
}) })
} }
_onClear(event) { _onClear(event) {
// The dropzone has just been cleared // The dropzone has just been cleared
// console.info(event);
console.info('onclear'); console.info('onclear');
} }
} }

3
assets/js/event-bus.js Normal file
View File

@@ -0,0 +1,3 @@
import Vue from 'vue';
window.EventBus = new Vue();
export const EventBus = window.EventBus;

View File

@@ -47,7 +47,6 @@ export default {
}, },
methods: { methods: {
search: function () { search: function () {
console.info(this.searchTerm);
axios.get('/book/search/' + this.searchTerm).then(response => { axios.get('/book/search/' + this.searchTerm).then(response => {
this.books = response.data; this.books = response.data;
}); });

View File

@@ -21,7 +21,8 @@
<td class="text-end">{{ formatSize(file.fileSize) }}</td> <td class="text-end">{{ formatSize(file.fileSize) }}</td>
<td>{{ file.extension }}</td> <td>{{ file.extension }}</td>
<td><a :href="'/file/'+ file.id" class="link-secondary">download</a></td> <td><a :href="'/file/'+ file.id" class="link-secondary">download</a></td>
<td><a :href="'/file/delete/'+file.id" class="link-danger">remove</a></td> <td><a :href="'/file/delete/'+file.id" @click.prevent="deleteFile(file.id)" class="link-danger">remove</a>
</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -31,9 +32,13 @@
<script> <script>
import axios from 'axios'; import axios from 'axios';
import {EventBus} from "../event-bus";
export default { export default {
name: 'Files', name: 'Files',
components: {
EventBus
},
data() { data() {
return { return {
files: [] files: []
@@ -42,9 +47,15 @@ export default {
mounted() { mounted() {
this.getFiles(); this.getFiles();
}, },
created() {
window.EventBus.$on('fileUploaded', this.getFiles);
},
methods: { methods: {
deleteFile: function (fileId) {
axios.get(window.location.origin + '/file/delete/' + fileId).then(() => this.getFiles())
},
formatSize: function (bytes) { formatSize: function (bytes) {
if (bytes == 0) { if (bytes === 0) {
return "0.00 B"; return "0.00 B";
} }
var e = Math.floor(Math.log(bytes) / Math.log(1024)); var e = Math.floor(Math.log(bytes) / Math.log(1024));

View File

@@ -10,6 +10,7 @@ use App\Repository\BookRepository;
use App\Repository\FileRepository; use App\Repository\FileRepository;
use App\Service\FileService; use App\Service\FileService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@@ -86,27 +87,15 @@ class BookController extends AbstractController
} }
#[Route('/{id}', name: 'app_book_show', methods: ['GET', 'POST'])] #[Route('/{id}', name: 'app_book_show', methods: ['GET', 'POST'])]
public function show(Book $book, Request $request, FileRepository $fileRepository): Response public function show(Book $book, Request $request, FileRepository $fileRepository, FileService $fileService): Response
{ {
$fileForm = $this->createForm(FileType::class); $fileForm = $this->createForm(FileType::class);
$fileForm->handleRequest($request); $fileForm->handleRequest($request);
if ($fileForm->isSubmitted() && $fileForm->isValid()) { if ($fileForm->isSubmitted() && $fileForm->isValid()) {
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile[] $ebooks */ /** @var UploadedFile[] $ebooks */
$ebook = $request->files->get('file')['file']; $ebook = $request->files->get('file')['file'];
$file = new File(); $fileService->saveFile($ebook, $book);
$file->setFileName(trim($ebook->getClientOriginalName()));
$file->setFileSize($ebook->getSize());
$file->setExtension($ebook->guessClientExtension());
$file->setBook($book);
$fileRepository->add($file, true);
$ebook->move(
$this->getParameter('book_files'),
'ebook_' . $book->getId() . '_' .
md5($file->getFileName()) . '.' .
$file->getExtension()
);
} }
return $this->renderForm('book/show.html.twig', [ return $this->renderForm('book/show.html.twig', [
@@ -127,7 +116,8 @@ class BookController extends AbstractController
Request $request, Request $request,
Book $book, Book $book,
BookRepository $bookRepository, BookRepository $bookRepository,
FileRepository $fileRepository FileRepository $fileRepository,
FileService $fileService
): Response { ): Response {
$form = $this->createForm(BookType::class, $book); $form = $this->createForm(BookType::class, $book);
$form->handleRequest($request); $form->handleRequest($request);
@@ -141,23 +131,11 @@ class BookController extends AbstractController
); );
} }
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile[] $ebooks */ /** @var UploadedFile[] $ebooks */
$ebooks = $request->files->get('book')['ebook']; $ebooks = $request->files->get('book')['ebook'];
if (count($ebooks) > 0) { if (count($ebooks) > 0) {
foreach ($ebooks as $ebook) { foreach ($ebooks as $ebook) {
$file = new File(); $fileService->saveFile($ebook, $book);
$file->setFileName(trim($ebook->getClientOriginalName()));
$file->setFileSize($ebook->getSize());
$file->setExtension($ebook->guessClientExtension());
$file->setBook($book);
$fileRepository->add($file, true);
$ebook->move(
$this->getParameter('book_files'),
'ebook_' . $book->getId() . '_' .
md5($file->getFileName()) . '.' .
$file->getExtension()
);
} }
} }

View File

@@ -55,7 +55,7 @@ class BookType extends AbstractType
]) ])
// ->add('cover', FileType::class, ['mapped' => false, 'data_class' => null, 'required' => false]) // ->add('cover', FileType::class, ['mapped' => false, 'data_class' => null, 'required' => false])
->add('cover_url', TextType::class, ['mapped' => false, 'help' => 'Fill in the field with a link to a cover image to use it as a cover for the book.', 'label'=> 'Cover url', 'required' => false]) ->add('cover_url', TextType::class, ['mapped' => false, 'help' => 'Fill in the field with a link to a cover image to use it as a cover for the book.', 'label'=> 'Cover url', 'required' => false])
->add('cover', DropzoneType::class, ['mapped' => false, 'data_class' => null, 'required' => false, 'attr' => ['data-controller' => 'mydropzone', 'accept' => "image/*", 'placeholder' => 'Drag and drop or browse']]) ->add('cover', DropzoneType::class, ['mapped' => false, 'data_class' => null, 'required' => false, 'attr' => ['accept' => "image/*", 'placeholder' => 'Drag and drop or browse']])
; ;
} }

View File

@@ -22,7 +22,7 @@ class FileType extends AbstractType
'data_class' => null, 'data_class' => null,
'required' => true, 'required' => true,
'attr' => [ 'attr' => [
'data-controller' => 'mydropzone', 'data-controller' => 'filedropzone',
'accept' => ".pdf, .epub, .mobi", 'accept' => ".pdf, .epub, .mobi",
'placeholder' => 'Drag and drop or browse' 'placeholder' => 'Drag and drop or browse'
] ]

View File

@@ -2,35 +2,68 @@
namespace App\Service; namespace App\Service;
use App\Entity\Book;
use App\Entity\File; use App\Entity\File;
use App\Repository\FileRepository; use App\Repository\FileRepository;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileService class FileService
{ {
private Filesystem $fileSystem; private Filesystem $fileSystem;
private string $bookFiles; private string $bookFiles;
private FileRepository $fileRepository;
public function __construct(string $bookFiles, FileSystem $filesystem) public function __construct(string $bookFiles, FileSystem $filesystem, FileRepository $fileRepository,)
{ {
$this->bookFiles = $bookFiles; $this->bookFiles = $bookFiles;
$this->fileSystem = $filesystem; $this->fileSystem = $filesystem;
$this->fileRepository = $fileRepository;
} }
/** /**
* @param File[] $files * @param Collection $files
* @return void * @return void
*/ */
public function removeFiles(Collection $files) public function removeFiles(Collection $files)
{ {
foreach ($files as $file) { foreach ($files as $file) {
$filePath = $this->bookFiles . '/' . 'ebook_' . $file->getBook()->getId() . '_' . $this->fileSystem->remove($this->getFilePath($file));
md5($file->getFileName()) . '.' .
$file->getExtension();
$this->fileSystem->remove($filePath);
} }
} }
public function getFilePath(File $file): string
{
return $this->bookFiles . DIRECTORY_SEPARATOR . $this->getFileName($file);
}
public function getFileName(File $file): string
{
return 'ebook_' . $file->getBook()->getId() . '_' .
md5($file->getFileName()) . '.' .
$file->getExtension();
}
/**
* @param UploadedFile $ebook
* @param Book $book
* @return File
*/
public function saveFile(UploadedFile $ebook, Book $book): File
{
$file = new File();
$file->setFileName(trim($ebook->getClientOriginalName()));
$file->setFileSize($ebook->getSize());
$file->setExtension($ebook->guessClientExtension());
$file->setBook($book);
$this->fileRepository->add($file, true);
$ebook->move(
$this->bookFiles,
$this->getFileName($file)
);
return $file;
}
} }