You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.5:无法将Dropzone上传文件存入FileBag求助

Fixing Dropzone File Uploads in Laravel

Let's fix this step by step — I see a few key issues in your code that are preventing the files from reaching your Laravel backend:

Key Problems Identified

  • Duplicate Dropzone Targets: You have both a <form> with class="dropzone" and a <div> inside it also with class="dropzone". Even with autoDiscover: false, this creates confusion about which element Dropzone should bind to.
  • Mismatched Configuration Target: You're setting Dropzone.options.myAwesomeDropzone but your Dropzone element has an ID of dropzoneFileUpload — this configuration never gets applied to your actual Dropzone instance.
  • Unnecessary Submit Button: Dropzone handles file uploads via AJAX automatically (by default) — your manual submit button triggers a standard form POST instead of Dropzone's specialized file upload request, which is why no files are sent.

Fixed Code Implementation

Master Blade (testmaster.blade.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/dropzone.css">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">
</head>
<body>
    @yield('content')

    <script src="/dropzone.js"></script>
    <script type="text/javascript">
        Dropzone.autoDiscover = false;
        window.addEventListener('DOMContentLoaded', function() {
            // Initialize Dropzone on the correct element
            const myDropzone = new Dropzone("#dropzoneFileUpload", {
                url: "{{ url('/testUpload') }}",
                paramName: "file", // Matches the name Laravel will look for in $request->file('file')
                maxFilesize: 2, // MB
                addRemoveLinks: true,
                headers: {
                    'X-CSRF-TOKEN': "{{ csrf_token() }}" // Send CSRF token via header (more reliable)
                },
                init: function() {
                    // Optional: Add custom success/error handlers
                    this.on("success", function(file, response) {
                        console.log("File uploaded successfully:", response);
                    });
                    this.on("error", function(file, errorMessage) {
                        console.error("Upload failed:", errorMessage);
                    });
                }
            });
        });
    </script>
</body>
</html>

Child Blade View

@extends("testmaster")

@section('content')
<div class="container">
    <!-- Only one Dropzone target with unique ID -->
    <div id="dropzoneFileUpload" class="dropzone"></div>
</div>
@endsection

Controller (HomeController.php)

public function testUpload(Request $request) {
    // Check if files were received
    if ($request->hasFile('file')) {
        $file = $request->file('file');
        // Do something with the file (e.g., store it)
        $path = $file->store('uploads');
        return response()->json(['success' => true, 'path' => $path]);
    }

    return response()->json(['success' => false, 'message' => 'No file received']);
}

Route (unchanged)

Route::get('/test','HomeController@test');
Route::post('/testUpload','HomeController@testUpload');

Why This Works

  • Single Dropzone Target: We removed the redundant <form> and only initialize Dropzone on the dedicated <div> — no more conflicting targets.
  • Correct Configuration Binding: The Dropzone instance is created directly with all necessary settings (no separate Dropzone.options that doesn't match the element ID).
  • CSRF Token via Header: Sending the CSRF token in the request header is more reliable for AJAX uploads than adding it to params, and aligns with Laravel's default CSRF protection.
  • Automatic AJAX Uploads: Dropzone will upload files as soon as they're dropped (or selected) — no need for a submit button. If you want to upload all files at once, you can add a custom button and use myDropzone.processQueue() in its click handler.

Testing the Fix

  1. Clear your browser cache to ensure old JS/CSS isn't interfering.
  2. Visit /test and drop a file into the Dropzone area.
  3. Check your browser's dev tools (Network tab) — you should see a POST request to /testUpload with the file data included.
  4. The controller will now receive the file in $request->file('file') and return a JSON response confirming success.

内容的提问来源于stack exchange,提问作者stoneferry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:33:21