在Laravel中使用Ajax上传图片。

时间:2018-09-21 12:05:36

标签: ajax laravel

我必须将带有ajax的数据插入数据库中,现在它将数据插入到数据库中,但不上传图像。

ajax代码

 $(document).on("click","#save", function(){
        jQuery.ajax({
            method :'post',
            url:''+APP_URL+'/products/add_product',
            data:$("#product_form").serialize(),
            success: function(response){ 
             $("#product_list").load("<?php echo url('products/tblproducts');?>").fadeIn("slow")

                }
            });    
  });

“ product_form”是表单的ID。

路线

         Route::post('products/add_product','admin\ProductsController@add_new_product');

控制器功能

public function add_new_product(Request $request){
  try{ 
        DB::beginTransaction(); 

         $product_image = NULL;
        if ($request->hasFile('product_photo')){ 
            $ext = $request->product_image->getClientOriginalExtension();
            $product_image = uniqid().".".$ext; 
            $file = $request->file('product_image');
            $destinationPath = public_path("products");
            $file->move($destinationPath, $product_image); 
        }
         $bdata['product_photo']=$product_image;
        $bdata['product_name']= $request->item_name;
        $bdata['product_barcode']= $request->barcode;   
        DB::table('tbl_products')->insert($bdata);
        DB::commit();
        $this->CreateMessages('add');
    }catch(\Exception $v){
         DB::rollback();
        $this->CreateMessages('not_added');
        throw $v;
    }

}

3 个答案:

答案 0 :(得分:0)

您必须修改:

data:$("#product_form").serialize()

成为:

data: new FormData("#product_form")

并且您的表单必须将enctype属性设置为multipart/form-data

答案 1 :(得分:0)

您可以按照以下步骤上传图像并序列化表单数据:

<script>
      var formData = new FormData($("#FormId")[0]);
    $.ajax({
        url:''+APP_URL+'/products/add_product',
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'application/json',
        headers: {
            'X-CSRF-TOKEN': "{{ csrf_token() }}"
        },
        success: function (data, textStatus, jqXHR) {
               // do what you want
        },
        error: function (jqXHR, textStatus, errorThrown) {

        }
    }); 
</script>

答案 2 :(得分:0)

Try below code to upload image:

`$(document).on("click","#save", function(){
 var fd = new FormData();
 fd.append('product_photo',$('#id_of_image_uploader').prop('files')[0]);
 fd.append('item_name', $('#id_of_item_name').val());
 fd.append('barcode', $('#id_of_barcode').val());

 jQuery.ajax({
            method :'post',
            url:''+APP_URL+'/products/add_product',
            data: fd,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){ 
             $("#product_list").load("<?php echo url('products/tblproducts');?>").fadeIn("slow")
                }
            });
});`