【问题标题】:Image upload Laravel 5.3 using ajax图片上传 Laravel 5.3 使用 ajax
【发布时间】:2017-06-04 03:01:53
【问题描述】:

我这里有问题。我正在开发我的 Web 应用程序,我希望它通过 ajax 连接到我的 API。我正在尝试通过 ajax 从客户端(即网络)的表单将图像发送到我的 api。

所以,这是我在客户端的表单..

{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
  {{ csrf_field() }}

    <div class="row" style="margin-top:10%;">
      <div class="col s12  center">
        <img class="circle" id="image_url" src=""></a>
        {!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
      </div>
    </div>
    <div class="row">
      <div class="input-field col s6">
        {{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
        {{ Form::label('herbal_name', 'Herbal Name') }}
      </div>
      <div class="input-field col s6">
        {{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
        {{ Form::label('scientific_name', 'Scientific Name') }}
      </div>
    </div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}

这是我的 ajax,仍在客户端

<script type="text/javascript">
 $(".add").click(function() {
    $.ajax({
        url: 'http://127.0.0.1/identificare_api/public/api/plants',
        data: new FormData($("#addplant")[0]),
        type: "POST",
        success: function( msg ) {
            console.log(msg);
        },
        error: function(){
            alert('pangit');
        }
    });
 });
</script>

编辑:在我的 api 中,我只有这个

return json_encode($request->file('image_url'));

我在这里缺少什么?我错过了什么吗?

更新:我尝试应用@bfcior 的答案,但是当我尝试console.log(base64img) 时,它会返回这个非常长的字符串,并且比您预期的要长。

click for image

【问题讨论】:

    标签: php jquery ajax forms laravel-5.3


    【解决方案1】:

    我不完全确定这是否是问题所在,但您不应该使用按钮而不是提交吗?我想使用提交会阻止 ajax 工作,因为表单正在提交到服务器进行处理。

    编辑:单击提交按钮时会发生什么?告诉我们将帮助 stackoverflow 用户诊断问题。

    【讨论】:

    • 更改提交到按钮时仍然不行。无论如何,当我单击提交按钮时,它会返回 null。
    • 可能是您的 ajax 调用无法访问您指定的 url。您是使用 XAMP 还是 Homestead 进行本地测试?
    • null 来自我指定的网址。是的,我正在使用 xampp 并在客户端运行 php artisan serve
    • 我要做的是更改 API 以返回硬编码消息,例如“它可以工作!”然后测试。如果您仍然收到空响应,那么您知道问题是您的 ajax 调用无法访问该 url。如果它返回消息,那么问题出在您的 API 上。
    【解决方案2】:

    您使用以下方式处理文件:

    $request->file('image_url');
    

    https://laravel.com/docs/5.3/requests#files

    【讨论】:

    • 检查全局变量dd($_FILES);中是否有东西
    【解决方案3】:

    另一种方法是将 img 转换为 base64 并将其作为参数传递。然后在您的控制器/路由中,您可以解码 base64 并保存到文件(如果需要)。

    {{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
        <div class="row" style="margin-top:10%;">
          <div class="col s12  center">
            <img class="circle" id="image_url" src=""></a>
            {!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
          </div>
        </div>
        <div class="row">
          <div class="input-field col s6">
            {{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
            {{ Form::label('herbal_name', 'Herbal Name') }}
          </div>
          <div class="input-field col s6">
            {{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
            {{ Form::label('scientific_name', 'Scientific Name') }}
          </div>
        </div>
    {{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
    {{ Form::close() }}
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        });
    
        var base64img = null;
    
        $(document).ready(function() {
            $('#image').change(function(){
    
                var file = this.files[0];
                var reader  = new FileReader();
    
                reader.addEventListener("load", function () {
                    base64img = reader.result;
                }, false);
    
    
                if (file) {
                    reader.readAsDataURL(file);
                }
    
            });
    
            $(".add").click(function(e) {
    
                e.preventDefault();
    
                $.ajax({
                    url: 'http://127.0.0.1:8000/identificare_api/public/api/plants',
                    data: $("#addplant").serialize() + '&image_url=' + base64img,
                    type: "POST",
                    success: function( msg ) {
                        console.log(msg);
                    },
                    error: function(){
                        alert('pangit');
                    }
                });
             });
        });
    </script>
    

    和路线

    Route::post('identificare_api/public/api/plants', function (Request $request) {
        return json_encode($request->all());
    });
    

    【讨论】:

    • 为什么$_POST['image_url'] 太长了?
    • 请参考我上面的更新,看看base64img 会返回什么。
    • 我的意思是当我尝试使用 base64_decode($_POST['image_url'] 解码它时,$_POST['image_url'] 很长。当我尝试返回解码后的$_POST['image_url'] 时,它返回 false。根据 (base64decode.net/php-base64-decode),如果输入包含 base64 字母表之外的字符,base64_decode() 将返回 false。
    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2020-07-04
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多