Файл не распознан ОШИБКА «Вызов функции-члена store () при нулевом значении» при загрузке файла Laravel

#javascript #php #ajax #laravel #datatables

#javascript #php #ajax #laravel #таблицы данных

Вопрос:

Я использую Laravel, Ajax с таблицами данных для управления моей информацией, все работало нормально, но мне нужно загрузить в него файлы. Но я получаю вызов функции-члена store () при null.

Вот код функций контроллера (post и fetch):

     function postdata(Request $request)
    {
        $validation = Validator::make($request->all(), [

            'referencia'  => 'required',
            'tipo_equipo'  => 'required',
            'tipo_servicio'  => 'required',
            'id_reporte'  => 'required',

        ]);

        $error_array = array();
        $success_output = '';
        if ($validation->fails())
        {
            foreach($validation->messages()->getMessages() as $field_name => $messages)
            {
                $error_array[] = $messages;
            }
        }
        else
        {

            if($request->get('button_action') == 'update')
            {


                $servicio = Servicio::find($request->get('servicio_id'));
                $servicio->referencia = $request->get('referencia');
                $servicio->tipo_equipo = $request->get('tipo_equipo');
                $servicio->tipo_servicio = $request->get('tipo_servicio');
                $servicio->id_reporte = $request->get('id_reporte');
                $servicio->imagen_inicio = $request->file('imagen_inicio')->store('public/img/servicio');
                $servicio->imagen_fin = $request->get('imagen_fin');
                $servicio->pdf_reporte = $request->get('pdf_reporte');
                $servicio->save();
                $success_output = '<div class="alertaTables alert alert-success">Servicio Actualizado</div>';
            }
        }
        $output = array(
            'error'     =>  $error_array,
            'success'   =>  $success_output
        );
        echo json_encode($output);
    }

    function fetchdata(Request $request)
    {
        $id = $request->input('id');
        $servicio = Servicio::find($id);

        $output = array(
            'id_usuario' => $servicio->id_usuario,
            'id_cliente' => $servicio->id_cliente,
            'referencia' => $servicio->referencia,
            'tipo_equipo' => $servicio->tipo_equipo,
            'tipo_servicio' => $servicio->tipo_servicio,
            'id_reporte' => $servicio->id_reporte,
            'imagen_inicio' => $servicio->imagen_inicio,
            'imagen_fin' => $servicio->imagen_fin,
            'pdf_reporte' => $servicio->pdf_reporte
        );
        echo json_encode($output);
    }
  

Вот код моего скрипта:

      $('#servicio_form').on('submit', function(event){
        event.preventDefault();
        var form_data = $(this).serialize();
        $.ajax({
            url:"{{ route('mis-servicios.postdata') }}",
            method:"POST",
            data:form_data,
            dataType:"json",
            success:function(data)
            {
                if(data.error.length > 0)
                {
                    var error_html = '';
                    for(var count = 0; count < data.error.length; count  )
                    {
                        error_html  = '<div class="alertaTables alert alert-danger">' data.error[count] '</div>';
                    }
                    $('#form_output').html(error_html);
                    window.setTimeout(function() {
                        $(".alert").fadeTo(500, 0).slideUp(500, function(){
                            $(this).remove(); 
                         });
                    }, 5000);
                }
                else
                {
                    $('#form_output').html(data.success);
                    $('#mis-servicios_table').DataTable().ajax.reload();

                    window.setTimeout(function() {
                        $(".alert").fadeTo(500, 0).slideUp(500, function(){
                            $(this).remove(); 
                         });
                    }, 5000);
                }
            }
        })
    });



    $(document).on('click', '.edit', function(){
        var id = $(this).attr("id");
        $.ajax({
            url:"{{ route('mis-servicios.fetchdata') }}",
            method:'get',
            data:{id:id},
            dataType:'json',
            success:function(data)
            {
                $('#id_usuario').val(data.id_usuario);
                $('#id_cliente').val(data.id_cliente);
                $('#referencia').val(data.referencia);
                $('#tipo_equipo').val(data.tipo_equipo);
                $('#tipo_servicio').val(data.tipo_servicio);
                $('#id_reporte').val(data.id_reporte);
                $('#imagen_inicio').val(data.imagen_inicio);
                $('#imagen_fin').val(data.imagen_fin);
                $('#pdf_reporte').val(data.pdf_reporte);
                $('#servicio_id').val(id);
                $('#servicioModal').modal('show');
                $('#action').val('Editar');
                $('.modal-title').text('Editar Servicio');
                $('#button_action').val('update');
            }
        })            
    });

  

И вот код моего blade.php

 <main class="content">
                <div class="container-fluid p-0">
                    <h1 class="h3 mb-3">Mis Servicios</h1>

                    <br />
                    <table id="mis-servicios_table" class="table table-striped table-bordered dataTable" style="width:100%">
                        <thead>
                            <tr style="background-color: white;">
                                <th>Usuario</th>
                                <th>Cliente</th>
                                <th>Referencia</th>
                                <th>Equipo</th>
                                <th>Servicio</th>
                                <th>No. de Reporte</th>
                                <th>Fecha Inicio</th>
                                <th>Fecha Fin</th>
                                <th>Status</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                    </table>
                </div>
                <div id="servicioModal" class="modal fade" role="dialog">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <form method="post" id="servicio_form" enctype="multipart/form-data">
                                <div class="modal-header">
                                <h4 class="modal-title">Añadir Servicio</h4>
                                <button type="button" class="close" data-dismiss="modal">amp;times;</button>
                                </div>
                                <div class="modal-body">
                                    {{csrf_field()}}
                                    <span id="form_output"></span>
                                    <div class="form-group">
                                        <label>Usuario</label>
                                        <select name="id_usuario" id="id_usuario" class="form-control" disabled>
                                                <option value="">Elige el Usuario</option>
                                            @foreach($useres as $user)
                                                <option value="{{ $user->id }}">{{ $user->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Cliente</label>
                                        <select name="id_cliente" id="id_cliente" class="form-control" disabled>
                                                <option value="">Elige el Cliente</option>
                                            @foreach($nombreCliente as $nombreCliente)
                                                <option value="{{ $nombreCliente->id }}">{{ $nombreCliente->nombre_cliente }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Referencia</label>
                                        <input type="text" name="referencia" id="referencia" class="form-control" readonly/>
                                    </div>
                                    <div class="form-group">
                                        <label>Tipo de Equipo</label>
                                        <input type="text" name="tipo_equipo" id="tipo_equipo" class="form-control" readonly/>
                                    </div>
                                    <div class="form-group">
                                        <label>Tipo de Servicio</label>
                                        <input type="text" name="tipo_servicio" id="tipo_servicio" class="form-control" readonly/>
                                    </div>
                                    <div class="form-group">
                                        <label>ID Reporte</label>
                                        <input type="text" name="id_reporte" id="id_reporte" class="form-control" />
                                    </div>
                                    <div class="form-group">
                                        <label>Imagen ID Equipo</label>
                                        <input type="file" name="imagen_inicio" id="imagen_inicio" class="form-control" />
                                    </div>
                                    <div class="form-group">
                                        <label>Imagen Servicio Terminado</label>
                                        <input type="file" name="imagen_fin" id="imagen_fin" class="form-control" />
                                    </div>
                                    <div class="form-group">
                                        <label>Reporte en PDF</label>
                                        <input type="file" name="pdf_reporte" id="pdf_reporte" class="form-control" />
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <input type="hidden" name="servicio_id" id="servicio_id" value="" />

                                    <input type="hidden" name="button_action" id="button_action" value="insert" />
                                    <input type="submit" name="submit" id="action" value="Añadir" class="btn btn-info" />
                                    <button id="cerrarModal" type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
</main>
  

Ответ №1:

Это не позволяет вам сохранить файл, потому что файл не попадает на сервер, потому что вы используете AJAX для выполнения запроса, для отправки файлов через AJAX попробуйте это:

 $('#servicio_form').on('submit', function(event){
   event.preventDefault();

   // init formData and get files
   let formData = new FormData($('#servicio_form')[0]);
   let imagenInicio = $('#imagen_inicio')[0].files[0];
   let imagenFin= $('#imagen_fin')[0].files[0];
   let pdfReporte= $('#pdf_reporte')[0].files[0];

   // append files to formData
   formData.append('imagen_inicio', imagenInicio);
   formData.append('imagen_fin', imagenFin);
   formData.append('pdf_reporte', pdfReporte);

   // in AJAX disable contentType, processData and cache
   $.ajax({
      url:"{{ route('mis-servicios.postdata') }}",
      method:"POST",
      dataType:"json",
      data: formData,       // change this and the following options
      contentType: false, 
      processData: false,
      cache: false,
      success: function(data) {
         // your code...
      }
   });
});
  

Комментарии:

1. @Dharman Это действительно работает, но файлы не сохраняются в папках, ссылки отображаются как 404 не найдено, и если я нажимаю на кнопку редактирования, я получаю эту ошибку «Не удалось установить свойство ‘value’ в ‘HTMLInputElement’: Этот элемент ввода принимает имя файла, которое может быть программно установлено только в пустую строку.»