【问题标题】:Upload image via ajax in Laravel 5在 Laravel 5 中通过 ajax 上传图片
【发布时间】:2017-09-28 10:23:46
【问题描述】:

我的代码有点问题。

我无法在控制器中接收输入图像。然后我使用print_r($input); 我收到空数组。

我的js代码:

$(document).on('click', '#photo-upload #upload-button', function(e) {
    e.preventDefault();

    $.ajax({

        url: "/photo/upload/",
        data: new FormData($("#photo-upload")[0]),
        dataType:'json',
        type:'GET',
        processData: false,
        contentType: false,

        success: function ( data ) {

            alert("succes!");
        },

        error: function ( data ) {

            alert("error");

        }
    });
});

我的表格:

            <div class="full-cell">

                <span>Название</span>
            </div>

            <div class="full-cell">
                <input type="text" name="name" class="input-full" id="name">
            </div>

            <div class="full-cell">

                <span>Описание</span>
            </div>

            <div class="full-cell">
                <textarea name="description" id="description" cols="30" rows="3"></textarea>
            </div>

            <div class="full-cell">

                <span>Загрузить в альбом:</span>

                <select name="album" id="album">

                    @foreach ($albums as $album)
                        @include('partials.select._album_names')
                    @endforeach
                </select>
            </div>

            <div class="file">

                <input type="file" name="image" id="fileInput"/>
            </div>

            <div class="window-footer">

                <button type="button" class="auth-button btn-sec" id="upload-cancel">Отмена</button>
                <button type="submit" class="auth-button btn-advanced" id="upload-button" hidden="">Загрузить</button>
            </div>
        </form>

我的控制器:

public function store(Request $request) {

    $user = Auth::user();                                                           //Данные учетной записи
    $input = Input::all();
    $image = Input::file('image');                                                  //Записываем картинку в переменную

    print_r($input);

    $filename  = $user->username . '.' . $image->getClientOriginalExtension();      //Создаем новое имя файла

    $date = date('Y-m-d');                                                          //Получаем дату
    $path = "user_data/photos/$date/";                                              //Создаем путь до оригинала
    $thumbnail_path = "user_data/photos/$date/thumbnail/";                          //Создаем путь до миниатюры

    File::makeDirectory("$path", 0775, true, true);                                 //Директория для фото
    File::makeDirectory("$thumbnail_path", 0775, true, true);                       //Директория для миниатюры

    $image->move($path, $filename);                                                 //Сохраняем картинку на сервер


    $photo = "$path" . $filename;                                                   //Адрес фото
    $thumbnail = "$thumbnail_path" . $filename;                                     //Адрес миниатюры

    File::copy($photo, $thumbnail);                                                 //копируюм фото в миниатюры

    $image = Image::make($thumbnail)->fit(153,90)->save();

    $new_photo = new Photo;

    $new_photo->owner_id    = $user->id;
    $new_photo->name        = $input['name'];
    $new_photo->description = $input['description'];
    $new_photo->photo       = "/$photo";
    $new_photo->thumbnail   = "/$thumbnail";
    $new_photo->album_id    = $input['album'];

    $new_photo->save();

}   

【问题讨论】:

    标签: javascript php laravel upload


    【解决方案1】:

    Ajax 代码

      var formData = new FormData();
                formData.append("file",$('#fileForm16')[0].files[0]);
                formData.append("password",$("#textPassword").val());
    
      $.ajax({
                        url: "{{url("api/uploadfiles")}}",
                        data: formData,
                        type: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
                        processData: false, // NEEDED, DON'T OMIT THIS
                        // ... Other options like success and etc
    
                        success: function (response) {
                            console.log(response);
    
    
                        }
                    });
    

    Laravel 代码

     if (($request->hasFile('file'))) {
                $destinationPath = 'uploads/files'; // upload path
                $extension = $request->file('file')->getClientOriginalExtension(); // getting image extension
    
                $tempName = $request->file("file")->getClientOriginalName();
                $fileName = uniqid("MW") . '.' . $extension; // renameing image
                $request->file('file')->move($destinationPath, $fileName); // uploading file to given path
                // sending back with message
                $imagepath = $destinationPath.'/'.$fileName;
    
    
            }
    

    【讨论】:

      【解决方案2】:

      我找到了解决这个问题的方法!即使在我的上传按钮上,我也需要使用不同的。 我确实使用了这个事件: $(document).on('click', '#photo-upload #upload-button', function(e) - 这不起作用! 现在我使用这个事件: $(document).on('submit', '#photo-upload', function(e) 和 code 工作正常!!!谢谢大家。希望这对任何人都有帮助)

      【讨论】:

        【解决方案3】:

        尝试改用请求。

        $request->all()
        

        【讨论】:

          猜你喜欢
          • 2019-11-06
          • 1970-01-01
          • 1970-01-01
          • 2016-08-21
          • 1970-01-01
          • 2015-07-28
          • 2020-01-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多