Skip to content

Beautiful Open-Source Form Builder

1.7 KB
Raw Blame
<?php

namespace App\Http\Controllers\Content;

use App\Http\Controllers\Controller;
use App\Service\Storage\FileUploadPathService;
use App\Service\Storage\UploadSecurityService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class FileUploadController extends Controller
{
    /**
     * Upload file to local temp
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload(Request $request, UploadSecurityService $uploadSecurityService)
    {
        $request->validate([
            // Temporary uploads include respondent attachments, not only form assets.
            'file' => 'required|file|max:' . (config('opnform.public_uploads.max_file_size') / 1024),
        ]);

        try {
            $inspection = $uploadSecurityService->inspectUploadedFile($request->file('file'));
        } catch (\App\Exceptions\UploadSecurityException $exception) {
            throw ValidationException::withMessages([
                'file' => [$exception->getMessage()],
            ]);
        }

        $uuid = (string) Str::uuid();
        $path = FileUploadPathService::getTmpFileUploadPath($uuid);

        if ($inspection->isSvg) {
            if (!Storage::put($path, $inspection->sanitizedContents)) {
                throw new \RuntimeException('File storage failed.');
            }
        } else {
            if (!Storage::putFileAs(FileUploadPathService::getTmpFileUploadPath(), $request->file('file'), $uuid)) {
                throw new \RuntimeException('File storage failed.');
            }
        }

        return response()->json([
            'uuid' => $uuid,
            'key' => $path,
        ], 201);
    }
}