$request->file('logoImg') всегда null

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

В большинстве ответов на этом же форуме я обнаружил, что мне нужно добавить атрибут, я включил загрузку файлов в php, max_file_size более 512 МБ и т. д. и т. д. и ничего не получается.

Когда я проверяю $request->input('logoImg'), получаю имя файла, которое я выбрал в форме, но если я изменяю на $request->file('logoImg'), ожидается любой загружаемый объект файла, но возвращает NULL.

У меня много ума от этого, и я считаю, что проблема в среде конфигурации Laravel, повторяю, я считаю.

Вот мой код.

Вот код формы в файле xxxx.blade.php

<form method = "POST" action = "{{ route ('socioActualizar', $socio->Id) }}" enctype=”multipart/form-data”>



      <div class = "row" style = "padding:15px;">


         <!-- Main content for option-->
          <div class = "card shadow mb-4" style = "width:100%">
            <div class = "card-header py-3">
              <h6 class = "m-0 font-weight-bold text-primary">Socio: {!! $socio->Nombre_Apellidos !!}</h6>
              <button type = "button"style = "background:skyblue; float:right; padding:5px; margin-top:5px;" onclick = "location.href = '{{ route('cuotas',$socio->Id) }}'">Ver cuotas</button>
            </div>

          </div>

    <!-- /.container-fluid -->
            <div class = "card shadow mb-4" style = "width:50%; padding:15px; float:left;">
            <div class = "card-header py-3">
              <h7 class = "m-0 font-weight-bold text-primary">Datos Personales</h7>
            </div>
            {{ csrf_field() }}
            <label for = "Numero_Socio">Número de socio</label>
            <input type = "number" name = "Numero_Socio" id = "Numero_Socio" value = "{{ $socio->Numero_Socio }}" disabled style = "text-align:right; width:25%; padding:5px;">

            <label for = "Nombre_Apellidos">Nombre y Apellidos</label>
            <input type = "text" name = "Nombre_Apellidos" id = "Nombre_Apellidos" value = "{{ $socio->Nombre_Apellidos }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "DNI">Dni / Nif</label>
            <input type = "text" pattern = "[0-9A-Za-z]{9}" placeholder = "Formato 12345678X" name = "DNI" id = "DNI" value = "{{ $socio->DNI }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Direccion">Dirección</label>
            <textarea name = "Direccion" id = "Direccion" rows = "5" cols = "1" style = "text-align:left; width:100%; padding:5px;">{{ $socio->Direccion }}</textarea>

            <label for = "Poblacion">Población / Municipio</label>
            <input type = "text" name = "Poblacion" id = "Poblacion" value = "{{ $socio->Poblacion }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Calle">Provincia</label>
            <input type = "text" name = "Calle" id = "Calle" value = "{{ $socio->Calle }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Cp_Provincia" style = "width:100%;">Código postal</label>
            <input type = "number" name = "CP_Provincia" id = "CP_Provincia" value = "{{ $socio->CP_Provincia }}" style = "text-align:left; width:25%; padding:5px;">

            <label for = "Correo_Electronico" style = "width:100%;">Correo Electrónico</label>
            <input type = "email" name = "Correo_Electronico" id = "Correo_Electronico" value = "{{ $socio->Correo_Electronico }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Telefono" style = "width:100%;">Teléfono</label>
            <input type = "text" name = "Telefono" id = "Telefono" value = "{{ $socio->Telefono }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Fecha_Alta" style = "width:100%;">Fecha de alta</label>
            <input type = "date" name = "Fecha_Alta" id = "Fecha_Alta" value = "{{ $socio->Fecha_Alta }}" disabled style = "text-align:left; width:30%; padding:5px;">

            <label for = "Fecha_Baja" style = "width:100%;">Fecha de baja</label>
            <input type = "date" name = "Fecha_Baja" id = "Fecha_Baja" value = "{{ $socio->Fecha_Baja }}" style = "text-align:left; width:30%; padding:5px;">




    </div>

    <div class = "card shadow mb-4" style = "width:50%; padding:15px; float:left;">
            <div class = "card-header py-3">
              <h7 class = "m-0 font-weight-bold text-primary">Datos Profesionales</h7>
            </div>
            <label for = "Quien_lo_Presenta">Quién lo presenta</label>
            <input type = "text" name = "Quien_Lo_Presenta" id = "Quien_Lo_Presenta" value = "{{ $socio->Quien_Lo_Presenta }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Cargo">Cargo</label>
            <input type = "text" name = "Cargo" id = "Cargo" value = "{{ $socio->Cargo }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Ejercito">Ejército</label>
            <input type = "text" name = "Ejercito" id = "Ejercito" value = "{{ $socio->Ejercito }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Cuerpo_Servido">Cuerpo Servido</label>
            <input type = "text" name = "Cuerpo_Servido" id = "Cuerpo_Servido" value = "{{ $socio->Cuerpo_Servido }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Tercio_Brigada">Tercio Brigada</label>
            <input type = "text" name = "Tercio_Brigada" id = "Tercio_Brigada" value = "{{ $socio->Tercio_Brigada }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Bandera">Bandera</label>
            <input type = "text" name = "Bandera" id = "Bandera" value = "{{ $socio->Bandera }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Compañia">Compañía</label>
            <input type = "text" name = "Compañia" id = "Compañia" value = "{{ $socio->Compañia }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Localidad">Localidad</label>
            <input type = "text" name = "Localidad" id = "Localidad" value = "{{ $socio->Localidad }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Provincia">Provincia</label>
            <input type = "text" name = "Provincia" id = "Provincia" value = "{{ $socio->Provincia }}" style = "text-align:left; width:100%; padding:5px;">

            <label for = "Fecha_Ingreso" style = "width:100%;">Fecha de ingreso</label>
            <input type = "date" name = "Fecha_Ingreso" id = "Fecha_Ingreso" value = "{{ $socio->Fecha_Ingreso }}" style = "text-align:left; width:30%; padding:5px;">

            <label for = "Fecha_Licencia" style = "width:100%;">Fecha de Licencia</label>
            <input type = "date" name = "Fecha_Licencia" id = "Fecha_Licencia" value = "{{ $socio->Fecha_Licencia }}" style = "text-align:left; width:30%; padding:5px;">


    </div>
       <div class = "card shadow mb-4" style = "width:30%; padding:15px; float:left;">
           @if ($socio->Imagen == '')
                <img id = "avatar" src = "../img/soldier.png" style = "width:125px; height:125px;">
           @else
                <img id = "avatar" src = "{{ $socio->Imagen }}" style = "width:125px; height:125px;">
           @endif

           <input type = "file" name = "logoImg" id = "Img" style = "padding:5px; margin-top:5px;" onchange = "showMyImage(this)" >

        </div>

      <div class = "card shadow mb-4" style = "width:70%; padding:15px; float:left;">

            <label for = "Observaciones">Observaciones</label>
            <textarea name = "Observaciones" id = "Observaciones" rows = "8" cols = "1" style = "text-align:left; width:100%; padding:5px;">{{ $socio->Observaciones }}</textarea>

        </div>



     <!-- Main content for option-->
          <div class = "card shadow mb-4" style = "width:100%; height:55px;">

           <input type = "submit" Value = "Guardar Cambios" id = "guardar_cambios" style = "background:skyblue; position:absolute; right:10px; padding:5px; margin-top:5px;">

          </div>



  </div>
  </form>

Это мой файл маршрута web.php

Route::get('/socios', 'SociosController@sociosView')->name('socios');
Route::get('/socio/{id}','SociosController@sociosSelect')->name('socio');
Route::post('/socioActualizar/{id}','SociosController@socioActualizar')-> name('socioActualizar');
Route::get('/cuotas/{id}','CuotasController@verCuotasSocio')->name('cuotas');

И, наконец, код в контроллере

 public function socioActualizar(Request $request, $id)
{
    $socio = Socio::where('Id',$id)->first();
    $socio->Nombre_Apellidos = $request->input('Nombre_Apellidos');
    $socio->DNI = $request->input('DNI');
    $socio->Direccion = $request->input('Direccion');
    $socio->Calle = $request->input('Calle');
    $socio->Poblacion = $request->input('Poblacion');

    $socio->CP_Provincia = $request->input('CP_Provincia');
    $socio->Telefono = $request->input('Telefono');
    $socio->Correo_Electronico = $request->input('Correo_Electronico');

  //  $socio->Fecha_Alta = $request->input('Fecha_Alta');
    $socio->Fecha_Baja = $request->input('Fecha_Baja');

    $socio->Quien_Lo_Presenta = $request->input('Quien_Lo_Presenta');
    $socio->Cargo = $request->input('Cargo');
    $socio->Ejercito = $request->input('Ejercito');
    $socio->Cuerpo_Servido = $request->input('Cuerpo_Servido');
    $socio->Tercio_Brigada = $request->input('Tercio_Brigada');
    $socio->Bandera = $request->input('Bandera');
    $socio->Compañia = $request->input('Compañia');
    $socio->Localidad = $request->input('Localidad');
    $socio->Provincia = $request->input('Provincia');
    $socio->Fecha_Ingreso = $request->input('Fecha_Ingreso');
    $socio->Fecha_Licencia = $request->input('Fecha_Licencia');
    $socio->Observaciones = $request->input('Observaciones');
    //logica de la subida de imagen en laravel

    //obtenemos el campo file definido en el formulario
    $name = $request->input('logoImg'); // returns name of file selected
    $name = $request->file('logoImg'); // returns null Why??
    $request->logoImg->store('uploads');
    if ($request->hasFile('logoImg')){
        $logoImage = $request->file('logoImg');
        $name = $logoImage->getClientOriginalName();
        //indicamos que queremos guardar un nuevo archivo en el disco local
        Storage::disk('local')->put($name,  File::get($logoImage));
    }

    //obtenemos el nombre del archivo
    $socio->Imagen = $name;
    $socio->save();

    return Redirect::to('socios/');
}

Я тоже заблудился на этом, казалось бы, простом шаге, но он не работает, конечно, это небольшая ошибка, но я не могу ее найти.

Большое спасибо.

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Оживление вашего приложения Laravel: Понимание режима обслуживания
Оживление вашего приложения Laravel: Понимание режима обслуживания
Здравствуйте, разработчики! В сегодняшней статье мы рассмотрим важный аспект управления приложениями, который часто упускается из виду в суете...
Установка и настройка Nginx и PHP на Ubuntu-сервере
Установка и настройка Nginx и PHP на Ubuntu-сервере
В этот раз я сделаю руководство по установке и настройке nginx и php на Ubuntu OS.
Коллекции в Laravel более простым способом
Коллекции в Laravel более простым способом
Привет, читатели, сегодня мы узнаем о коллекциях. В Laravel коллекции - это способ манипулировать массивами и играть с массивами данных. Благодаря...
Как установить PHP на Mac
Как установить PHP на Mac
PHP - это популярный язык программирования, который используется для разработки веб-приложений. Если вы используете Mac и хотите разрабатывать...
0
0
158
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

У меня нет конкретного ответа на ваш вопрос, но мой подход к решению вашей проблемы состоял бы в том, чтобы на секунду выйти за пределы ваших рамок и использовать для отладки простой PHP.

В этом случае я бы посмотрел на ваш суперглобальный $_FILES и установил, правильно ли загружается ваш файл.

Если вы ничего там не получаете, я бы посмотрел на ваш <form> и инспектор в Chrome, чтобы убедиться, что ваш файл отправляется правильно. Я не знаю, было ли это вашим копированием и вставкой, но кавычки на вашем enctype выглядят подозрительно.

$_FILES возвращает [] (пустой массив), но я изменю кавычки в атрибутах формы и проверю это....

Mario Rodríguez 07.02.2019 17:05

ВЫ ВЕЛИКИЙ!, Это проблема, ЦИТАТЫ, которые я изменил на простые (') и РАБОТАЕТ ОТЛИЧНО. Боже, мне еще многому предстоит научиться. Ок ПРОБЛЕМА РЕШЕНА.

Mario Rodríguez 07.02.2019 17:10

@MarioRodríguez, $file = $request->file('photo'); работал на вас после того, как вы исправили цитаты? Или вы используете $_FILES superglobal?

cmac 08.02.2019 21:21

Здесь я копирую код, который использую для загрузки изображений.
Чтобы создать миниатюру и сохранить изображение, я использовал Изображение вмешательства — PHP-библиотеку для обработки изображений и манипулирования ими.

Здесь объясняется, как его установить:
http://image.intervention.io/getting_started/installation

 if ($request->file('image')){
      $imageFile = $request->file('image');
      $imageName = time() . '.' . 'jpg';  //$imageName = $teaserImageFile->hashName();
      $imageSubdir = "events_teaser";
      $imageWidth = "968";
      $thumbWidth = "310";

     $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
      $event->image = $imageName;
           }


// **********************************************************************
    /**
     * Upload image on server
     *
     * @param  $imageFile - the file to upload
     * @param  $imageName - the file name
     * @param  $imageSubdir - the subdir in /storage/app/public/images/..
     * @return none
     */
    function uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth){

        // Create dir if not exist (in /storage/app/public/images/..)
            if (!\Storage::disk('public')->has('images/'.$imageSubdir.'/')){
                \Storage::disk('public')->makeDirectory('images/'.$imageSubdir.'/');
            }

            $destinationPath = "app/public/images/".$imageSubdir."/";

            // Resize the image with Intervention - http://image.intervention.io/api/resize
                // -  resize and store the image to a width of 300 and constrain aspect ratio (auto height)
                // - save file as jpg with medium quality
                $image = \Image::make($imageFile->getRealPath())
                                ->resize($imageWidth, null, 
                                    function ($constraint) {
                                        $constraint->aspectRatio();
                                })
                                ->save(storage_path($destinationPath . $imageName), 75); 

            // Create the thumb            
                $image->resize($thumbWidth, null, 
                    function ($constraint) {
                        $constraint->aspectRatio();
                })
                ->save(storage_path($destinationPath . "thumb_".$imageName), 75); 

    }

Другие вопросы по теме