diff --git a/Controller/UploadController.php b/Controller/UploadController.php index 57ba0ef64e978f47af934982bbed7f06972bfd68..6f75b842dbac5e7a9b9fe9c0dfd7183f66046dae 100644 --- a/Controller/UploadController.php +++ b/Controller/UploadController.php @@ -102,47 +102,71 @@ class UploadController extends Controller */ public function putContentAction(Request $request, UploadedFile $file) { - $this->validateCsrfToken($request); + $this->validateCsrfToken($request); - if(null !== $range = $request->headers->get('Content-Range', null)) { - $matches = []; - if(!preg_match('@^bytes (\d+)-(\d+)/(\d+)$@', $range, $matches)) { - throw new BadRequestHttpException("Invalid Content-Range"); - } + list($offset, $maxlen, $complete) = $this->handleRangeHeader($request); - $start = intval($matches[1]); - $end = intval($matches[2]); - $total = intval($matches[3]); + // Demande un filehandle plutôt que charger le contenu en mémoire + $input = $request->getContent(true); + $file->copyFrom($input, $maxlen, $offset); + fclose($input); - if($start < 0 || $start >= $end || $end >= $total) { - throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE); + if($complete) { + return $this->completeUpload($file); } - $offset = $start; - $maxlen = 1 + ($end - $start); - $complete = $end === ($total-1); - } else { - $offset = 0; - $maxlen = PHP_INT_MAX; - $complete = true; + return $this->createResponse(Response::HTTP_OK, 'Chunk received'); } - // Demande un filehandle plutôt que charger le contenu en mémoire - $input = $request->getContent(true); - $file->copyFrom($input, $maxlen, $offset); - fclose($input); + /** + * + * @param Request $request + * @return array + */ + protected function handleRangeHeader(Request $request) + { - if(!$complete) { - return $this->createResponse(Response::HTTP_OK, 'Chunk received'); + if(null === $range = $request->headers->get('Content-Range', null)) { + return [0, PHP_INT_MAX, true]; + } + + $matches = []; + if(!preg_match('@^bytes (\d+)-(\d+)/(\d+)$@', $range, $matches)) { + throw new BadRequestHttpException("Invalid Content-Range"); } - $this->fileManager->completed($file); + $start = intval($matches[1]); + $end = intval($matches[2]); + $total = intval($matches[3]); + + if($start < 0 || $start >= $end || $end >= $total) { + throw new HttpException(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE); + } + + return [$start, 1 + ($end - $start), $end === ($total-1)]; + } + + /** + * + * @param UploadedFileInterface $file + * @return Response + */ + protected function completeUpload(UploadedFileInterface $file) + { + $status = Response::HTTP_OK; + $message = 'File uploaded'; + try { + $this->fileManager->completed($file); + } catch(RejectedFileException $ex) { + $status = Response::HTTP_FORBIDDEN; + $message = 'File rejected: '.$ex->getMessage(); + } $parameters = ['id' => $file->getId()]; return $this->createResponse( - Response::HTTP_OK, - 'File uploaded', + $status, + $message, [ 'files' => [ array_merge(