This commit is contained in:
2025-07-29 22:20:51 +02:00
parent 2558363a67
commit 327e382694
4 changed files with 147 additions and 62 deletions

View File

@ -3,4 +3,6 @@ oneup_uploader:
avatar:
frontend: dropzone
logo:
frontend: dropzone
frontend: dropzone
file:
frontend: dropzone

View File

@ -3,7 +3,9 @@
namespace App\Controller;
use App\Service\FileService;
use Oneup\UploaderBundle\Uploader\Response\ResponseInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@ -45,11 +47,44 @@ class FileController extends AbstractController
}
}
#[Route('/user/file/{domain}/{id}/uploadmodal', name: 'app_files_uploadmodal', methods: ['GET'])]
public function upload(string $domain, int $id, Request $request): Response
#[Route('/user/uploadmodal/{domain}/{id}', name: 'app_files_uploadmodal', methods: ['GET'])]
public function uploadmodal(string $domain, int $id, Request $request): Response
{
$relativePath = $request->query->get('path', '');
return $this->render('file\upload.html.twig', [
'useheader' => false,
'usemenu' => false,
'usesidebar' => false,
'endpoint' => 'file',
'domain' => $domain,
'id' => $id,
'path' => $relativePath,
]);
}
#[Route('/user/uploadfile', name: 'app_files_uploadfile', methods: ['POST'])]
public function upload(Request $request): Response|ResponseInterface
{
/** @var UploadedFile $file */
$file = $request->files->get('file');
$domain = $request->query->get('domain');
$id = $request->query->get('id');
$relativePath = $request->query->get('path', '');
if (!$file || !$domain || !$id) {
return new Response('Invalid parameters', 400);
}
$baseDir = $this->getParameter('kernel.project_dir').'/uploads/'.$domain.'/'.$id.'/'.ltrim($relativePath, '/');
if (!is_dir($baseDir)) {
mkdir($baseDir, 0775, true);
}
$originalName = $file->getClientOriginalName();
$file->move($baseDir, $originalName);
return new JsonResponse(['success' => true]);
}

View File

@ -11,11 +11,7 @@
{% if editable %}
<div class="mb-3">
<form method="post" enctype="multipart/form-data" class="d-flex gap-2 align-items-center" id="upload-form-{{ domain }}-{{ id }}">
<input type="file" name="file" required>
<input type="hidden" name="path" value="{{ path }}">
<button type="submit" class="btn btn-sm btn-primary">Uploader</button>
</form>
<a class="btn btn-info" style="max-width:100%; margin-bottom:15px;" data-bs-toggle="modal" data-bs-target="#mymodal" onClick="ModalLoad('mymodal','Upload','{{ path('app_files_uploadmodal',{domain:domain, id:id,path:path}) }}');" title='Upload'>Upload</a>
</div>
{% endif %}
@ -50,72 +46,79 @@
</div>
<script>
(function () {
function initFileBrowser(container) {
if (!container) return;
$(function () {
function refreshContainer(containerId, path) {
const $oldContainer = $('#' + containerId);
const base = $oldContainer.data('base-path');
container.addEventListener('click', function (e) {
// Navigation
if (e.target.classList.contains('file-nav')) {
e.preventDefault();
const path = e.target.dataset.path;
refreshContainer(container, path);
}
// Suppression
if (e.target.classList.contains('btn-delete')) {
e.preventDefault();
if (!confirm('Supprimer ce fichier ?')) return;
const pathToDelete = e.target.dataset.path;
const currentPath = container.dataset.currentPath || '';
fetch('/user/file/' + container.dataset.domain + '/' + container.dataset.id + '/delete', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
},
body: JSON.stringify({ path: pathToDelete })
})
.then(res => res.json())
.then(data => {
if (data.success) {
// Rafraîchit après suppression
refreshContainer(container, currentPath);
} else {
alert('Erreur : ' + data.error);
}
})
.catch(err => alert('Erreur lors de la suppression : ' + err.message));
$.get(base, { path: path }, function (html) {
console.log(html);
const $doc = $('<div>').html(html);
const $newContainer = $doc.find('#' + containerId);
console.log(containerId);
if ($newContainer.length) {
console.log("HHHHHHHHHHHHHHHHHHHH");
$oldContainer.replaceWith($newContainer);
initFileBrowser($newContainer); // rebind events
}
});
}
function refreshContainer(oldContainer, path) {
const domain = oldContainer.dataset.domain;
const id = oldContainer.dataset.id;
const base = oldContainer.dataset.basePath;
function initFileBrowser($container) {
const containerId = $container.attr('id');
fetch(base + '?path=' + encodeURIComponent(path))
.then(response => response.text())
.then(html => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const newContainer = doc.getElementById(oldContainer.id);
if (newContainer) {
oldContainer.replaceWith(newContainer);
newContainer.dataset.currentPath = path;
initFileBrowser(newContainer); // re-binde sur le nouveau DOM
// Clear any previous bindings (important!)
$container.off('click');
// Navigation dossier
$container.on('click', '.file-nav', function (e) {
e.preventDefault();
const path = $(this).data('path');
refreshContainer(containerId, path);
});
// Suppression fichier ou dossier
$container.on('click', '.btn-delete', function (e) {
e.preventDefault();
if (!confirm('Supprimer ce fichier ?')) return;
const pathToDelete = $(this).data('path');
const currentPath = $container.data('current-path');
$.ajax({
url: '/user/file/' + $container.data('domain') + '/' + $container.data('id') + '/delete',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ path: pathToDelete }),
success: function (res) {
if (res.success) {
refreshContainer(containerId, currentPath);
} else {
alert('Erreur : ' + res.error);
}
},
error: function (xhr) {
alert('Erreur lors de la suppression : ' + xhr.responseText);
}
});
});
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.file-browser').forEach(initFileBrowser);
// Init navigateur fichiers
const containerId = 'file-browser-{{ domain }}-{{ id|e('html_attr') }}';
const $browser = $('#' + containerId);
initFileBrowser($browser);
// Rafraîchir après fermeture modale
$('#mymodal').on('hidden.bs.modal', function () {
const $browser = $('#' + containerId);
const currentPath = $browser.data('current-path') || '';
refreshContainer(containerId, currentPath);
});
})();
});
</script>
</div>

View File

@ -0,0 +1,45 @@
{% extends 'base.html.twig' %}
{% block localstyle %}
<style>
body {
background-color: transparent;
}
</style>
{% endblock %}
{% block body %}
<a class="btn btn-secondary" onClick="closeModal();">Annuler</a>
<form action="{{ path('app_files_uploadfile', {
domain: domain,
id: id,
path: path
}) }}"
class="dropzone" id="myDropzone" style="margin-top:10px"></form>
{% endblock %}
{% block localscript %}
<script>
Dropzone.options.myDropzone = {
paramName: "{{endpoint}}",
maxFilesize: 20, // MB
parallelUploads: 5,
uploadMultiple: false,
dictDefaultMessage: "Déposez vos fichiers ici pour les téléverser",
successmultiple: function (files, response) {
console.log("multi uploaded", files);
},
queuecomplete: function () {
// Quand tous les fichiers sont uploadés, on ferme la modale et rafraîchit le navigateur
window.parent.$("#mymodal").modal('hide');
if (typeof window.parent.refreshFileBrowser === 'function') {
window.parent.refreshFileBrowser(); // à définir côté parent
}
}
};
function closeModal() {
window.parent.$("#mymodal").modal('hide');
}
</script>
{% endblock %}