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

Posted

技术标签:

【中文标题】Laravel - 在数据库中保存或插入图像数组 - Laravel【英文标题】:Laravel - Saving or Inserting Array of Images in Database - Laravel 【发布时间】:2019-04-21 11:17:21 【问题描述】:

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

P.S 我这里有 ajax,所以它有一个 id

这是我的观点

  !! 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() !!

这是我的控制器,它将存储或保存图像

 $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();

我的 AJAX 代码

<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>

【问题讨论】:

为什么要两次申报form?不需要第二条语句 【参考方案1】:
$('#add_name').serialize() using this you can't get image object in post using ajax.

你应该使用表单数据

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

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

以下更改

你的看法

!! 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() !!

对于控制器功能,你应该使用 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();  
                 
          );  
     );

【讨论】:

我是 laravel 新手,可以编辑上面的代码吗? 我正在使用 laravel 集体,这就是为什么 您能帮我吗?我只需要你修改我的代码谢谢 好吧..这看起来很合乎逻辑,但是这个呢?? if ($image) array_push($promotion_images, $postImage); 嘿先生,我可以成功插入图像.. 但现在的问题是当我插入 2 个或更多图像时,图像没有插入到数据库中

以上是关于Laravel - 在数据库中保存或插入图像数组 - Laravel的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5:将图像网址作为数组插入列

如何使用关系在laravel中的数据库中插入嵌套的二维数组

Laravel 存储/插入数组值到数据库 Mysql

数据仅在 Laravel 应用程序中插入最后一个数组

Laravel插入或更新数组,多行

在视图中显示图像 Laravel 6