【问题标题】:How to insert Images into db using ajax post request in laravel?如何在 laravel 中使用 ajax 发布请求将图像插入数据库?
【发布时间】:2018-02-07 17:12:40
【问题描述】:

Laravel 视图:

<form  enctype="multipart/form-data" method="post" name="imagesform" id="imagesform" >
    <input type="hidden" name="_token" value="{{ csrf_token()}}">
    <div>
        <label id="show" for="files" class="button">Upload photo</label>
        <input id="files" name="images" style="visibility:hidden;" type="file">
    </div> 
    <button type="submit"  class="save" id="saveImage" style="border-radius: 8px; padding: 5px 15px;">SAVE</button>
</form>

这是我上传图片的代码(它发生在我的引导模型中)。当我上传图片时,点击提交按钮,图片应该插入到数据库中,同样应该被检索并显示在视图上页面。

Ajax 代码:

$("#saveImage").click(function(e){
    // var formdata=new FormData($("#imagesform")[0]);
    //alert(formdata);
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });
    $.ajax({
        url: 'saveImages/{{$dataId}}',
        type: 'POST',
        data:new FormData($("#imagesform")),
        success: function (data) {
            alert(data)
        },
        cache: false,
        processData: false
    });
    return false;
});

这是ajax代码,我试过了,但是formdata的alert显示[object FormData],浏览器控制台显示Method not allowed exception

Laravel 路线:

Route::post('saveImages/{dataId}',['as' => 'saveImages','uses'=>'priceDetails@saveImages']);

控制器:

public function saveImages(Request $imagesform,$dataId)
{
    if (Input::hasFile('images'))
    {
        $name  = $this->getImageId().".".$imagesform->file('images')->getClientOriginalExtension();   

        $image = $imagesform->file('images');        
        $resize = Image::make($image)->resize(700, 300)->encode($imagesform->file('images')->getClientOriginalExtension());
        $hash = md5($resize->__toString());

        $path = "public/" . $name;
        Storage::put($path, $resize->__toString());
    }
    $insertImages=new photosModel;
    $insertImages->imagesid=$this->getimagesId();
    $insertImages->deviceCategoryId=$dataId;
    $insertImages->uploadedImages=$name;
    $insertImages->save();
    return $this->formImages($dataId);

}

public function formImages($dataId){
    $dataId=$dataId;
    $images=photosModel::all();
    return view('addProductDetails1')->with('images',$images)->with('dataId',$dataId);
}

【问题讨论】:

  • var form = $('#imagesform')[0];var formData = new FormData(form); 试试这个
  • 出现同样的错误
  • 再次提醒 [object FormData]
  • 尝试使用 cosole.log 而不是 alert() 并将其放入 ajax cache:false, contentType: false, processData: false,
  • 它以可展开的形式出现

标签: php jquery ajax twitter-bootstrap laravel-5.4


【解决方案1】:

我能够通过 Frankensteining 来自 here 的各种建议来解决类似的问题。该链接有一堆非常好的信息。您需要将 ajax 调用中的一些选项分配给 false。无论如何,这对我有用:

HTML

<input name="image" type="file" id="image">

Javascript

data = new FormData();
    jQuery.each(jQuery('#image')[0].files, function(i, file) {
        data.append('image', file);
    });

$.ajax({
    url: "submit/ajax",
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    data: data,
    success: function(response)
       {
          // Display your uploaded image on the page
       }
    });

PHP

Image::make($_FILES['image']['tmp_name']) >save("$myImageDirectory/$newImagegName");

【讨论】:

    【解决方案2】:

    要通过 AJAX 上传文件,您需要使用 XHR Level 2FormData 类需要在构造函数中使用 HTMLFormElement 才能发送其键值。

    你应该使用:

    new FormData( document.getElementById('imagesform') );
    

    你也可以使用 jQuery:

    new FormData( $("#imagesform").get(0) )
    

    在另一个类似问题中查看my answer 以获取更多信息。

    更新: 看到您的 cmets,您的问题也与 Laravel 路线有关。如果错误代码是 500 并且它显示消息“方法不允许”,您需要在 routes/web.php 中检查您的路由。请将错误的堆栈跟踪和您的路由文件(使用 pastebin 或类似文件)放在这里。

    【讨论】:

    • priceDetails 是我的控制器名称先生
    • 路由文件中的行??
    • 我很抱歉我没有很好地看到你的问题。请问你能把stacktrace的错误放在这里吗?
    • Route::post('saveImages/{dataId}',['as' => 'saveImages','uses'=>'priceDetails@saveImages']);
    • 要定位问题,我们需要逐步检查。首先将带有堆栈跟踪的错误消息(错误 500)放在这里。第二步是检查应用程序是否正在进入控制器的方法(调试它或放置一个简单的 var_dump)。最有可能的是它没有进入方法,所以问题可能出在路由文件上。请把所有路线都放在这里(使用 pastebin 或类似的)。
    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2015-07-18
    • 2018-01-27
    • 2016-06-05
    相关资源
    最近更新 更多