mysql - Laravel - 在数据库中保存或插入图像数组 - Laravel

标签 mysql arrays ajax laravel

我想将图像保存在数据库 mysql 上,我使用数组,虽然我可以插入一些东西,但它不是图像,而是空图像。这是我的 View 代码

P.S 我这里有ajax,这就是为什么它有一个id

Here is my VIEW

  {!! Form::open(['action'=>'Admin\PromotionsController@store', 'method' => 'POST','enctype'=>'multipart/form-data']) !!}
<div class="form-group">  
     <form name="add_name" id="add_name">  
          <div class="table-responsive">  
               <table class="table table-bordered" id="dynamic_field">  
                    <tr>  
                         <td> {{Form::file('promotion_image[]')}}</td>

                         <td>{{ Form::button('Add', ['class' => 'btn btn-success', 'id'=>'add','name'=>'add']) }}</td>
                    </tr>  
               </table>  
               {{Form::submit('submit', ['class'=>'btn btn-primary'])}}
          </div>  
     </form>  
</div>  
{!! Form::close() !!}

Here is my Controller that will store or save the images

 $this->validate($request, [
        'promotion_image' => 'required'
    ]);

   //Handle File Upload
   if($request->hasFile('promotion_image[]')){
    // Get FileName
    $filenameWithExt = $request->file('promotion_image[]')->getClientOriginalName();
    //Get just filename
    $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
    //Get just extension
    $extension = $request->file('promotion_image[]')->getClientOriginalExtension();
    //Filename to Store
    $fileNameToStore = $filename.'_'.time().'.'.$extension;
    //Upload Image
    $path = $request->file('promotion_image[]')->storeAs('public/promotion_images',$fileNameToStore);
    }else{
        $fileNameToStore='noimage.jpg';
    }

    $promotion = new Promotion;
    $promotion->promotion_image = $fileNameToStore;
    $promotion->save();

My AJAX code

<script>  
$(document).ready(function(){  
     var i=1;  
     $('#add').click(function(){  
          i++;  
          $('#dynamic_field').append('<tr id="row'+i+'"><td>{{Form::file('promotion_image[]',['class'=>'form-control name_list'])}}</td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
     });  
     $(document).on('click', '.btn_remove', function(){  
          var button_id = $(this).attr("id");   
          $('#row'+button_id+'').remove();  
     });  
     $('#submit').click(function(){            
          $.ajax({  
               url:"name.php",  
               method:"POST",  
               data:$('#add_name').serialize(),  
               success:function(data)  
               {  
                    alert(data);  
                    $('#add_name')[0].reset();  
               }  
          });  
     });  
});  
</script>

最佳答案

$('#add_name').serialize() using this you can't get image object in post using ajax.

你应该使用表单数据

var form = $('form')[0];
var formData = new FormData(form);

将 formData 作为 ajax 调用中的数据传递

以下更改

你的看法

{!! Form::open(['action'=>'Admin\PromotionsController@store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">   
    <div class="table-responsive">  
        <table class="table table-bordered" id="dynamic_field">  
           <tr>  
              <td> {{Form::file('promotion_image[]')}}</td>

              <td>{{ Form::button('Add', ['class' => 'btn btn-success', 'id'=>'add','name'=>'add']) }}</td>
           </tr>  
        </table>  
        {{Form::submit('submit', ['class'=>'btn btn-primary'])}}
    </div> 
</div>  
{!! Form::close() !!}

对于 Controller 功能,您应该使用 foreach

如果您使用的是最新的 laravel 版本

$this->validate($request, [
    'promotion_image' => 'required'
]);

if ($request->has('promotion_image'))
{
    $promotion_images = [];
    foreach ($request->file('promotion_image') as $key => $file)
    {
        $image = \Storage::put('promotion_image', $file); // your image path

        if ($image)
            array_push($promotion_images, $image);
    }

    $fileNameToStore = serialize($promotion_images);

}
else
{
    $fileNameToStore='noimage.jpg';
}
$promotion = new Promotion;
$promotion->promotion_image = $fileNameToStore;
$promotion->save();

或者按照你的逻辑

$this->validate($request, [
    'promotion_image' => 'required'
]);

if ($request->has('promotion_image'))
{   
    //Handle File Upload

    $promotion_images = [];
    foreach ($request->file('promotion_image') as $key => $file)
    {
        // Get FileName
        $filenameWithExt = $file->getClientOriginalName();
        //Get just filename
        $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
        //Get just extension
        $extension = $file->getClientOriginalExtension();
        //Filename to Store
        $fileNameToStore = $filename.'_'.time().'.'.$extension;
        //Upload Image
        $path = $file->storeAs('public/promotion_images',$fileNameToStore);
        array_push($promotion_images, $fileNameToStore);
    }

    $fileNameToStore = serialize($promotion_images);
}
else
{
    $fileNameToStore='noimage.jpg';
}

$promotion = new Promotion;
$promotion->promotion_image = $fileNameToStore;
$promotion->save();

并更改您的ajax脚本代码

更改提交方式

$('#submit').click(function(){  
        var form = $('#add_name')[0];
        var formData = new FormData(form);

          $.ajax({  
               url:"name.php",  
               method:"POST",  
               data:formData,  
               success:function(data)  
               {  
                    alert(data);  
                    $('#add_name')[0].reset();  
               }  
          });  
     });

关于mysql - Laravel - 在数据库中保存或插入图像数组 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368830/

相关文章:

javascript - 在 ko.observableArray 模型绑定(bind)问题中向下移动项目

php - 使用不显眼的 AJAX

javascript - 如何访问 javascript/typescript 中的重复项计数

使用数字数组作为关联数组的javascript

javascript - DataTables Ajax 未执行

javascript - PHP API + jQuery AJAX 调用 JSON 语法错误

php - 连接 3 个 MySQL 表时遇到问题,从两个表中检索数据 (CodeIgniter)

mysql - 在一组值中搜索一行的其他值

android - 由于android studio中的连接拒绝错误而无法将我的android应用程序与mysql连接?

php - 哪一个更好?何时或如果其他情况?