【问题标题】:how to store image in database using laravel 5.3 by passing data with ajax in controller?如何通过在控制器中使用 ajax 传递数据来使用 laravel 5.3 将图像存储在数据库中?
【发布时间】:2016-11-04 09:36:55
【问题描述】:

我创建了一个表格,如下所示 html代码:

<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
        <input style="margin-top:0px;" type="file" name="data1"  id="file1" class="btn btn-block btn-primary"/>
        <input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
        <a href="#" id="submit">link submit</a>
</form>

ajax 代码:

function create()
{

         alert();
         var file = document.getElementById('file1');
         var token = document.getElementById('token').value;
         var data1 = new FormData($("#upload_form")[0]);
         var route = "http://localhost:8080/form";
         console.log(FormData);
         console.log(data1);



         $.ajax({
                    type:'POST',
                    url: route,
                    headers: {'X-CSRF-TOKEN': token},
                    contentType: false,
                    processData: false,
                    data:{
                                'data1': data1,
                         },
                    success:function(e){
                        if(e == 0)  
                        {
                             alert("Success Full Created"); 

                        }
                        else
                        {   
                             alert("Error");
                        }
                    }
                 });
         }

这是我的路线:

Route::post('form', 'StoreController@newstore');

我创建了下面给出的控制器 控制器:

public function newstore(Request $request)
{
   $post = $request->file('data1');
   dd($post);
   //If there is error try dd($post) and let me know 
   // we need know if the data file image is passing to controller
   $imageName =  $post->getClientOriginalName();
   $imagemove= $post->move(public_path('images'),$imageName);
   $data123 = array (   "photo"=> $imageName,  );
   $check222 = DB::table('product') -> insert($data123);    
}

当我运行此代码时,它会显示此错误: RouteCollection.php 第 218 行中的 MethodNotAllowedHttpException:

【问题讨论】:

  • 在你的函数create()中的$formData之后,请插入console.log($formData);打开你的控制台浏览器,让我们看看结果
  • 我在控制台日志中得到了这个声明:FormData proto:FormData append:append() 构造函数:FormData() delete:delete() entries:entry() forEach:forEach () get : get() getAll : getAll() has : has() keys : keys() set : set() values : values() Symbol(Symbol.iterator) : () Symbol(Symbol.toStringTag) : "FormData " proto : 对象
  • 好的尝试改变你的类型:'get'到类型:'POST'
  • 更改类型后显示:未定义索引:data1
  • 打开网络浏览器提交文件,可能需要csfr令牌,

标签: php ajax laravel-5.2 laravel-5.3


【解决方案1】:

试试这个:

<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1"  id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
<a href="#" id="submit">link submit</a>
</form>

例如,如果您的路线是:

Route::post('form', 'yourcontroller@newstore');

JS

function create()
{

 var file = document.getElementById('file1');
 var route = "http://localhost:8000/form";
 var token = document.getElementById('token').value;
 var data1 = new FormData($("#upload_form")[0]);
 // we are using "$", i hope that you have jquery library 
/* alternative you can do:
   var getUpload = document.queryselector('#upload_form');
   var data1 = getUpload[0];
*/ 

//if there is error try also console.log(formData)
// if error try console-log(data1); info about the file uploaded
// if error token verify console.log(token); have the token serial number


$.ajax({
        type:'POST',
        url: route,
        headers: {'X-CSRF-TOKEN': token},
        contentType: false,
        processData: false,
        data:{
                    'data1': data1,
             },
        success:function(e){
            if(e == 0)  
            {
                 alert("Success Full Created"); 

            }
            else
            {   
                 alert("Error");
            }
        }
});}
var submit = document.querySelector('#submit').onclick= create

控制器

public function newstore(Request $request)
{
   $post = $request->file('data1');
   //If there is error try dd($post) and let me know 
   // we need know if the data file image is passing to controller
   $imageName =  $post->getClientOriginalName();
   $imagemove= $post->move(public_path('images'),$imageName);
   $data123 = array (   "photo"=> $imageName,  );
   $check222 = DB::table('product') -> insert($data123);   
}

如果您遇到错误,请告诉我!我希望它有效!

【讨论】:

  • 我已经尝试过您的代码,但显示此错误:RouteCollection.php 第 218 行中的 MethodNotAllowedHttpException:
  • 如果我传递数据而不是图像或文件,它可以正常使用此代码,但是当我传递文件或图像时它不起作用。
  • 使用链接 提交,因为如果您使用按钮,它将提交表单并且操作路线将不起作用。这是因为你有错误的路由集合。
  • 对点击链接做一个点击事件,例如:var submit = document.querySelector('#submit').onclick= create;添加链接提交并在您的函数创建后添加此js
  • 它显示了与“路由器集合”之前显示的相同的错误。运行代码后,我注意到它的数据甚至没有传递给控制器​​。
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 2018-11-16
  • 2014-12-08
  • 1970-01-01
相关资源
最近更新 更多