簡體   English   中英

Laravel 8 文件上傳與表格數據使用 AJAX 無法在數據庫中創建

[英]Laravel 8 File Upload with Form Data using AJAX unable to create in database

我是編碼新手,我想在我的blade.php 中的模態標簽中完成新產品表單后上傳產品圖像。

但是,我的數據無法發布到數據庫中,文件也沒有上傳到服務器。 請就我應該做些什么來解決這個問題提出建議。 提前致謝!

這是我的觀點:

<form action="{{route('merchant.product.new')}}" id="form" method="POST" enctype="multipart/form-data">
  @csrf
            <div class="modal-body">
                <div class="form-group">
                    <label for="prodName"> Product Name:</label> <small style="color: red">*</small>
                    <input type="text" id="prodName" class="form-control" name="prodName" value="" maxlength="55" placeholder="Product Name" required>
                </div>
                <div class="form-group">
                    <label for="prodCode"> Product Code:</label> <small style="color: red">*</small>
                    <input type="text" id="prodCode" class="form-control" name="prodCode" value="" maxlength="55" placeholder="Product Code" required>
                </div>
                <div class="form-group">
                    <label for="prodDesc"> Description:</label> <small style="color: red">*</small>
                
                    <textarea id="prodDesc"  name="prodDesc" rows="5" maxlength="255" placeholder="Product Description" class="form-control" required></textarea>
                </div>
                <div class="form-group">
                    <label for="age">Price:</label> <small style="color: red">*</small>
                    <input type="text" id="price" class="form-control" name="price" placeholder="Product Price" required>
                </div>
                <div class="form-group">
                    <label for="age">Quantity:</label>
                    <input type="number" id="quantity" class="form-control" name="Quantity" min="0" value="0">
                </div>
                <div class="form-group">
                    <label for="text">Feature Product</label>
                    <div class="switch">
                        <input type="checkbox" name="featured" id="featured" class="switch-input" value="1"/>
                        <div class="circle"></div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="image">Choose Main Image</label>
                    <input type="file" name="image" id="image">
                </div>
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary" id="new_productsave_btn" data-loading-text="<i class='fa fa-spinner fa-spin'></i> saving..">Save</button>
                <button type="button" class="btn btn-outline-primary" id="close_btn" data-dismiss="modal">Close</button>
    </div>
</form>

下面是我的腳本:

$(document).ready(function(e) {
            var selectedProductId = null;
            var selectedProductCode = null;
            var pageAction = null;
    
            //javascript to filter table
            var productsTable = $('#products_table').DataTable({ 
                stateSave: true,
                columnDefs: [{
                        "searchable": false,
                        "orderable": false,
                        "targets": 0
                },{
                        "searchable": true,
                        "orderable": true,
                        "targets": 1
                },{
                        "searchable": true,
                        "orderable": true,
                        "targets": 2
                },{
                        "searchable": false,
                        "orderable": false,
                        "targets": 3
                },{
                        "searchable": true,
                        "orderable": true,
                        "targets": 4
                },{
                        "searchable": true,
                        "orderable": true,
                        "targets": 5
                },{
                        "searchable": true,
                        "orderable": true,
                        "targets": 6
                },{
                        "searchable": false,
                        "orderable": false,
                        "targets": 7
                }],
                order: [[ 1, 'asc' ]]
            });
    
            productsTable.on( 'order.dt search.dt', function () {
                productsTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
                    cell.innerHTML = i+1;
                });
            }).draw();
    
            $('#addproduct_btn').click(function() {
                //pageAction = "add";
                $('#myModalNewProduct').modal({backdrop: 'static', keyboard: false});
                $('#myModalNewProduct .modal-title').html('New Product');
            });
    
            $('#new_productsave_btn').click(function() {
                let prodName = $('#prodName').val();
                let prodCode = $('#prodCode').val();
                let prodDesc = $('#prodDesc').val();
                let price = parseFloat($('#price').val().replace(/[^\d.]/g, ''));
                let quantity = $('#quantity').val();
                var featured = [];
                $('#featured').each(function(){
                  if ($(this).is(":checked")) {
                    featured.push($(this).val());
                  }
                });
    
                featured = featured.toString();
                if (prodCode == "") {
                    alert("Product Code can't be empty.");
                    return;
                }
                if (prodDesc == "") {
                    alert("description can't be empty.");
                    return;
                }
                if (price == "") {
                    alert("price can't be empty.");
                    return;
                }
                if (Number.isNaN(price)) {
                    alert("price must be numeric.");
                }
    
                //let url = pageAction == "add" ? @json($domain)+"/products/new" : @json($domain)+"/products/update";
                let data = {prodID: selectedProductId, prodName: prodName, prodCode: prodCode, prodDesc: prodDesc, quantity: quantity, price: price, 
                featured: featured,
                };
                $(this).data('original-text', $(this).html()).html($(this).data('loading-text')).prop('disabled', true);
                $.ajax({
                    type: "POST",
                    url: "{{ route('merchant.product.new') }}",
                    headers: { 
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',  
                        'Content-Type': 'application/json'
                    },
                    data: JSON.stringify(data),
                    dataType: "text",
                    success: function(data) { 
                        if (data == 0) {
                            $('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
                            showNotify("Product Code already exist", "error");
                            return;
                        } else if (data < 0) {
                            $('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
                            showNotify("Something went wrong", "error");
                            return;
                        }
                        showNotify("New product has been added successfully", "success");
                        location.reload();
                    },
                    error: function(data) {
                        $('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);                        
                        console.log(data);
                        showNotify("Something went wrong", "error");
                    }
                });
            });
});

下面是我的dd($request->all())

array:7 [▼
      "_token" => "pfPg4Grw7MXzDQwBeDAcBN83sZm06LK89GzlNdbY"
      "prodName" => "123213"
      "prodCode" => "123123"
      "prodDesc" => "123213"
      "price" => "123123"
      "Quantity" => "123"
      "image" => Illuminate\Http\UploadedFile {#359 ▼
        -test: false
        -originalName: "roasted-chicken.png"
        -mimeType: "image/png"
        -error: 0
        #hashName: null
        path: "C:\xampp\tmp"
        filename: "php6D72.tmp"
        basename: "php6D72.tmp"
        pathname: "C:\xampp\tmp\php6D72.tmp"
        extension: "tmp"
        realPath: "C:\xampp\tmp\php6D72.tmp"
        aTime: 2021-01-13 10:25:05
        mTime: 2021-01-13 10:25:05
        cTime: 2021-01-13 10:25:05
        inode: 5066549581112407
        size: 699931
        perms: 0100666
        owner: 0
        group: 0
        type: "file"
        writable: true
        readable: true
        executable: false
        file: true
        dir: false
        link: false
        linkTarget: "C:\xampp\tmp\php6D72.tmp"
      }
    ]

這是我的 controller 方法:

public function new (Request $request) {
        
        if ($this->isCodeExist($request->{'prodCode'})) {
            return 0;
        }
        else {
            $product = Product::create($request->all());
            if($request->hasFile('image')) {
                // Upload path
                $destinationPath = 'img/products/';
                // Get File
                $image = $request->file('image');
                // Get File Name
                $imageName = time().'_'.$image->getClientOriginalName();
                // Uploading File to given path
                $image->move($destinationPath,$imageName);
                
                // $fileModel->name = time().'_'.$req->file->getClientOriginalName();
                // $fileModel->file_path = '/storage/' . $filePath;
                // $fileModel->save();
            
                try {
                    //$db = new Product();
                    $product->prodName = $request->{'prodName'};
                    $product->prodCode = $request->{'prodCode'};
                    $product->prodImage = $imageName;
                    $product->prodDesc = $request->{'prodDesc'};
                    $product->price = $request->{'price'};
                    $product->quantity = $request->{'quantity'};
                    $product->featured = $request->input('featured') ? 1 : 0;
                    $dproductb->save();
                    return 1;
                } catch (\Illuminate\Database\QueryException $ex) {
                    Log::channel('merchant_error')->error($ex);
                    return -1;
                }
            }
        }
}

我已經設法讓它工作了,但是以前當我返回一個數值時,它會彈出我的 javascript 通知方法,但現在它只返回數值。 這里似乎有什么問題?

以下是我為新產品創建的 function:

public function create(Request $request)
    {
        if ($this->isCodeExist($request->{'prodCode'})) {
            return 0;
        } else {
            $product = Product::create($request->all());

            if ($request->hasFile('prodImage')) {
                $file = $request->file('prodImage');

                //Get file name with the time
                $name = time() . '_' . $file->getClientOriginalName();

                //Store file into public folder
                $file->move(public_path('img/products/'), $name);

                try {
                    //Insert ProdImage DB field with file name above
                    $product->prodImage = $name;
                    $product->save();
                    return 1; 
                    //back()->with('success_message', 'Product updated successfully!');
                } catch (\Illuminate\Database\QueryException $ex) {
                    Log::channel('merchant_error')->error($ex);
                    return -1;
                }
            }
        } 
    }

下面是我的 javascript 檢查文件上傳和創建新產品的 ajax 方法:

 $('create_product').submit(function(event) {
        event.preventDefault();
        var formData = new FormData($(this)[0]);
            $.ajax({
                url: '{{ route('merchant.product.create') }}',
                type: 'POST',              
                data: formData,
                success: function(data) { 
                    if (data == 0) {
                        $('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
                        showNotify("Product Code already exist", "error");
                        return;
                    } else if (data < 0) {
                        $('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);
                        showNotify("Something went wrong", "error");
                        return;
                    }
                    showNotify("New product has been added successfully", "success");
                    location.reload();
                },
                error: function(data) {
                    $('#new_productsave_btn').html( $('#new_productsave_btn').data('original-text')).prop('disabled', false);                        
                    console.log(data);
                    showNotify("Something went wrong", "error");
                }
            });

        });

下面是我的通知js function:

function showNotify(msg, className) {
            $.notify(
                msg, 
                { 
                    globalPosition:"top right", 
                    className: className
                }
            );
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM