Laravel使用Ajax / jquery通过模式上传图像

时间:2019-09-26 11:49:33

标签: php jquery ajax laravel upload

我正在制作一个包含库存的小型系统。我有一个products表,该表具有一个image列,该列代表特定产品的图片。我的问题是为什么我不能在Laravel项目中使用模态和Ajax代码上传?有谁知道如何解决这个问题?我已经花了两天的时间来解决该错误:

  

消息:“未定义索引:product_name”

我已经将字段填充到模型中。帮助将不胜感激。

output

模式代码

 <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
        <p style="font-weight: bold;">Name </p>
          <input   type="text" class="form-control" id="product_name"/>
          <p style="font-weight: bold;">Description </p>
          <input   type="text" class="form-control" id="description"/>
          <p style="font-weight: bold;">Price </p>
          <input   type="text" class="form-control" id="currentprice"/>
          {{-- <input style="text-transform:uppercase"   type="text" class="form-control" id="supplier_id"/> --}}
          <p style="font-weight: bold;">Supplier </p>
          <select class="form-control"  id="supplier_id"  >
              @foreach ($suppliers as $supplier)
          <option value="{{$supplier->id}}">{{$supplier->name}}</option>
              @endforeach
              </select>
         <p style="font-weight: bold;">Picture </p>
          <input  type="file" class="form-control" id="picture"/>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary" id="add_product">Add</button>
        </div>
      </div>
    </div>
  </div>

脚本

 $(document).ready(function() {
    //add
    $('#add_product').click(function(e) {
        e.preventDefault();
        var name = $('#product_name').val();
        var description = $('#description').val();
        var price = $('#currentprice').val();
        var supplier_id = $('#supplier_id').val();
        var image = $('#picture').val();

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: "{{    url('/product')     }}",
            method: 'post',
            enctype: 'multipart/form-data',
            processData: false, 
            contentType: false,
            data:{
                product_name: name,
                description: description,
                price: price,
                supplier_id: supplier_id,
                image: image,
            },
            success: function (res) {
                console.log(res);
                window.location.href = '{{route("products")}}'
            }
        });
    });
});

ProductsController.php

 public function store(Request $request)
    {
        $data = $request->all();
        $data['product_name'] = ($data['product_name']);
        $data['description'] = ($data['description']);
        $data['supplier_id'] = ($data['supplier_id']);
        $data['price'] = ($data['price']);



        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);
                $oldFilename = $products->image;
            //Update DB
                $products->image = $filename;
             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        Product::create($data);
        return response()->json($data);
    }

产品路线

//products
Route::resource('product', 'ProductsController');

2 个答案:

答案 0 :(得分:0)

当服务器需要JSON时,好像您向服务器发送了一个对象。尝试添加dataType:

$.ajax({
    url: "{{ url('/product') }}",
    method: 'post',
    enctype: 'multipart/form-data',
    contentType: false,
    dataType: 'json', // setting of data type
    data:{
        product_name: name,
        description: description,
        price: price,
        supplier_id: supplier_id,
        image: image,
    },
    success: function (res) {
        console.log(res);
        window.location.href = '{{route("products")}}'
    }
});

答案 1 :(得分:0)

我知道这个问题已经很老了,但我在过去几天遇到了同样的问题,所以我认为一个答案可能对其他开发者有用。

您只需要使用 FormData 而不是序列化您的表单。请注意,FormData 需要一个 HTMLFormElement,因此您需要将 [0] 添加到您的 jQuery 对象。而且您不必添加 dataType 指令。

这是我的代码:

$('#submit').on('click', function(e) {
    e.preventDefault();
    $(this).attr('disabled','disabled');
    var form = $(this).closest('form');
    jQuery.ajax({
        type: 'POST',
        processData: false,
        contentType: false,
        data: new FormData(form[0]),
        url: form.attr('action'),
        enctype: 'multipart/form-data',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        success: function (data) {
            $('#submit').removeAttr('disabled');
            // YOUR SUCCESS MANAGEMENT
        },
        error: function (e) {
            $('#submit').removeAttr('disabled');
            // YOUR ERROR MANAGEMENT
        }
    });
});