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

Laravel中jQuery File Upload无法正常工作的问题求助

问题分析与解决方案

Hey there, let's work through your issues step by step and fix the problems in your code:

1. Ajax代码未执行的问题

Your Ajax code has syntax errors and logical mistakes that are causing the browser to skip executing it:

Key Issues:

  • You nested $.ajaxSetup() directly inside the fileupload() configuration object, which is invalid syntax and breaks JS parsing.
  • $(meta[name="csrf-token"]) is missing quotes around the selector—should be $('meta[name="csrf-token"]').
  • You tried initializing the fileupload plugin inside the input change event, which leads to duplicate bindings and fails because of the earlier syntax error.
  • There are two extra }); at the end of your code, causing an unclosed structure.

Fixed Ajax Code:

$(document).ready(function(){
    // Global setup for CSRF Token (applies to all Ajax requests)
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Initialize fileupload plugin directly on the element
    $('#fileupload').fileupload({
        dataType: 'json',
        add: function (e, data) {
            alert('triggered'); // This should fire now
            $('#loading').text('Uploading...');
            data.submit();
        },
        done: function (e, data) {
            $('#loading').text('');
            $.each(data.result.files, function (index, file) {
                $('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
                
                // Cleanly update file_ids input
                const currentIds = $('#file_ids').val();
                $('#file_ids').val(currentIds ? `${currentIds},${file.fileID}` : file.fileID);
            });
        }
    });
});

2. CSRF Token Setup Question

Even if your master template has the CSRF Token meta tag, you still need to include it in Ajax requests—Laravel validates CSRF tokens for all POST requests by default.

Your original approach was incorrect. Here are two valid ways to handle this:

  • Option 1: Use global $.ajaxSetup() (like in the fixed code above) to automatically attach the token to every Ajax request.
  • Option 2: Set the header directly in the fileupload configuration:
$('#fileupload').fileupload({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    // Rest of your config...
});

Either works, but global setup is cleaner to avoid repeating code.

3. Controller Code Fixes

Your controller has several critical errors that will break the upload process:

  • $learnerFiles is undefined—you need to fetch files from the request.
  • $learner is undefined—you need to retrieve the user (either from the request or auth).
  • The return uses $photos which doesn't exist—it should be $files.
  • You should validate that uploaded files are valid before processing.

Fixed Controller Code Example:

public function uploadSubmit(Request $request){
    $files = [];
    // Get uploaded files from the request
    $learnerFiles = $request->file('photos');
    
    // Fetch the learner (adjust this to match your user retrieval logic)
    $learner = \App\Models\User::where('id_number', $request->input('idNumber'))->first();
    if(!$learner){
        return response()->json(['error' => 'Learner not found'], 404);
    }

    foreach($learnerFiles as $key => $learnerFile){
        // Only process valid files
        if($learnerFile->isValid()){
            $fileName = $request->input('idNumber') . '_' . $key . '.' . $learnerFile->extension();
            $path = $learnerFile->storeAs('public/uploads/learners', $fileName);
            
            // Save file record to database
            $file = \App\Models\FileUpload::create([
                'user_id' => $learner->id,
                'file_name' => $fileName,
                'path' => str_replace('public/', '', $path)
            ]);

            // Prepare response data
            $file_object = new \stdClass();
            $file_object->name = $fileName;
            $file_object->size = round(\Storage::size($path) / 1024, 2);
            $file_object->fileID = $file->id; // Use the FileUpload record ID, not user ID
            $files[] = $file_object;
        }
    }

    return response()->json(['files' => $files], 200);
}

Quick Debugging Tips

  • Open your browser's DevTools (F12) and check the Console tab for JS syntax errors—this is the first step to debugging Ajax issues.
  • Start with simplified code (e.g., just an alert in the add event) to confirm the plugin is working, then add more logic.
  • Make sure you've properly included the jQuery File Upload plugin's JS files—if fileupload() is undefined, the plugin isn't loaded.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:28:21