Использование Dropzone JS в Laravel 5.7 - PullRequest
0 голосов
/ 17 октября 2018

В моем приложении Laravel у меня есть загрузчик файлов, который использует ввод файла с массивом в качестве имени.

Примерно так: <input type="file" name="files[]" multiple required />

Это позволяет мне принимать несколько файловв виде массива.

Метод загрузки можно увидеть ниже:

 /**
     * Process uploading of multiple files, ensuring that the extension is within the given white list
     *
     * @param Request $request
     * @return void
     */
    public function bulkUpload(Request $request)
    {
        // Get every extension that we allowed
        $all_ext = implode(',', $this->allExtensions());

        $this->validate($request, [
            'files.*' => 'required|file|mimes:' . $all_ext . '|max:50000'
        ], 
        [
            'files.*.required' => 'Please select a file to upload',
            'files.*.file' => 'You may only upload files in this area',
            'files.*.mimes' => 'This type of file is not permitted on the Intranet'
        ]);

        // Initialize a file upload counter
        $fileCount = 0;

        // Get the category and department from the form
        $category = $request->get('category');

        // Check that the category is of a type we've set
        if (!in_array($category, $this->categories)) {
            return redirect()->back()->with([
                'error' => "The category you've selected is not valid"
            ]);
        }

        // Ensure that the request contains files
        if ($request->hasfile('files')) {
            // Loop through each file and add it to storage
            foreach ($request->file('files') as $file) {

                // Get the meta data for each file
                $name = $file->getClientOriginalName();
                $extension = strtolower($file->getClientOriginalExtension());
                $type = $this->getType($extension);
                $size = $file->getSize();

                // Upload all the given files to Storage, within a specific directory
                if ($category != '') {
                    $path = $file->storeAs('library/' . $category, $name);
                    $department = null;
                }

                // Grab the filepath so we can store it in the database
                $file->filepath = $path;

                // Create the database entries for the newly uploaded files
                FileMetaData::firstOrCreate(
                    [
                        'name' => $name,
                        'extension' => $extension
                    ],
                    [
                        'category' => $category,
                        'type' => $type,
                        'size' => $size,
                        'filepath' => $path
                    ]);

                $fileCount++;

                Log::info(auth()->user()->log_reference . "uploaded files into the template library: {$name}");
            }

            return redirect('editable/templates-and-tools')->with('success', $fileCount . ' files have been added');
        }
    }

Я попытался внедрить Dropzone.js в мой проект, поскольку использование файлового ввода было болезненным для пользователей.

Чтобы добиться этого, я добавил все необходимые зависимости и добавил элемент для Dropzone для инициализации.В своем клинке я добавил:

<div id="file" name="files[]" class="dropzone"></div>

Затем в моем скрипте я инициализировал Dropzone следующим образом:

<script>
    Dropzone.autoDiscover = false;

    var drop = new Dropzone('#file', {
        createImageThumbnails: false,
        maxFilesize: 50, // MB
        maxFiles: 2, 
        addRemoveLinks: true,
        url: "{{ route('uploads.upload') }}",
        headers: {
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
        }
    });
</script>

Я также изменил свой скрипт выгрузки для возвратаследующее после окончания цикла $file foreach.

return response()->json(
    'success', 200
);

Но я не получаю абсолютно ничего в консоли, и файлы не загружаются.

Я ожидал, что валидатор вернетошибка JSON, но это не так.

...