使用 AJAX 和 Laravel 导入 Excel 文件

问题描述 投票:0回答:1

我正在尝试在我的应用程序中使用 AJAX 和 Laravel 导入 Excel 文件。 excel导入的形式是内部形式(另一个形式内的形式)错误处理似乎部分工作,但错误消息并不总是在前端正确显示。

我的 JavaScript 代码:

$(document).ready(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $('#submitUnits').on('click', function(e) {
        e.preventDefault();

        var formData = new FormData();
        formData.append('unitsFile', $('#unitsFile')[0].files[0]);
        formData.append('buildingId', $('#buildingId').val());

        var buildingId = $('#buildingId').val();
        $.ajax({
            url: '/building-units-import/' + buildingId,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {

                console.log('successsss:' + response.errors);

                $('#errorMessages').empty();

                if (response.errors && response.errors.length > 0) {
                    $('#errorTable').show();
                    $.each(response.errors, function(index, error) {
                        var row = $('<tr>').appendTo('#errorMessages');
                        row.append($('<td>').text(error.row));
                        row.append($('<td>').text(error.message));
                    });
                } else {
                    $('#errorTable').hide();
                    alert('File imported successfully.');
                }
            },
            error: function(xhr) {
                console.log("error:" + xhr);
            }
        });
    });
});

导入Excel文件后: 在控制台中,它显示:

error:[object Object]

在网络预览中:它显示 422 错误代码以及实际的 Excel 错误:

{message: "القيمة المحددة 2.العقار غير موجودة. (و 6 أخطاء إضافية)",…} errors :  [["There was an error on row 2. القيمة المحددة العقار غير موجودة."],…] 0 :  ["There was an error on row 2. القيمة المحددة العقار غير موجودة."] 1 :  ["There was an error on row 3. القيمة المحددة العقار غير موجودة."] 2 :  ["There was an error on row 2. القيمة المحددة نوع الوحدة غير موجودة."] 3 :  ["There was an error on row 3. القيمة المحددة نوع الوحدة غير موجودة."] 4 :  ["There was an error on row 2. القيمة المحددة الطابق غير موجودة."] 5 :  ["There was an error on row 3. القيمة المحددة الطابق غير موجودة."] 6 :  ["There was an error on row 3. حقل عقد الدفاع المدني غير موجود."] message :  "القيمة المحددة 2.العقار غير موجودة. (و 6 أخطاء إضافية)"

但我想在成功案例中得到这些错误的响应。

而且,这就是我的控制器端点:

    public function import_building_units(Request $request, $building_id)
{
    $request->validate([
        'unitsFile' => 'required|file|mimes:xlsx,xls,csv', // Use 'unitsFile' as per your form field name
    ]);


    // Access the uploaded file directly
    $file = $request->file('unitsFile');

    $import = new BuildingUnitsImport($building_id);
    Excel::import($import, $file);

    $errors = $import->getErrors();

    if (empty($errors)) {
        // Import successful, return appropriate response
        return response()->json(['success' => 'File imported successfully']);
    } else {
        // Import failed, return detailed error messages
        return response()->json(['errors' => $errors]);
    }
}
javascript php jquery ajax laravel
1个回答
0
投票

以下行:

$request->validate([
    'unitsFile' => 'required|file|mimes:xlsx,xls,csv', // Use 'unitsFile' as per your form field name
]);

会抛出一个

ValidationException
。然后,这将根据请求类型(在您的情况下为 XHR)被捕获并返回,错误代码为
422

如果您想更改此行为,请捕获异常并自行返回。

try {
    $request->validate([
        'unitsFile' => 'required|file|mimes:xlsx,xls,csv', // Use 'unitsFile' as per your form field name
    ]);
} catch (ValidationException $ex) {
    return response()->json(['errors' => $ex->errors()->all()]);
}
© www.soinside.com 2019 - 2024. All rights reserved.