简体   繁体   English

使用Ajax上传图像Laravel 5.3

[英]Image upload Laravel 5.3 using ajax

I have a problem here. 我在这里有问题。 I am developing my web application and I want it to connect to my API through ajax. 我正在开发Web应用程序,并且希望它通过ajax连接到我的API。 I am trying to send an image to my api through ajax from my form in the client side, which is the web. 我正在尝试通过客户端(即网络)中的表单通过ajax将图像发送到api。

So, here's my form in the client side.. 所以,这是我在客户端的表格。

{{ 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() }}

Here's my ajax, still in the client side 这是我的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>

EDIT: and in my api, I just have this one 编辑:在我的api中,我只有这个

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

What am I missing here? 我在这里想念什么? Did I missed something? 我错过了什么吗?

UPDATE: I tried to apply the answer of @bfcior but when I try to console.log(base64img) , it will return this very long string and it's longer than you expected. 更新:我尝试应用@bfcior的答案,但是当我尝试console.log(base64img) ,它将返回这个很长的字符串,并且比您期望的更长。

click for image 点击查看图片

I'm not entirely sure if this is the issue but aren't you supposed to be using a button instead of a submit? 我不完全确定这是否是问题,但您不应该使用按钮而不是提交吗? I'd imagine using a submit is preventing the ajax from working because the form is being submitted to the server for processing. 我以为使用提交会阻止ajax正常工作,因为该表单已提交给服务器进行处理。

EDIT: What happens when you click the submit button? 编辑:单击提交按钮时会发生什么? Telling us will help stackoverflow users diagnose the problem. 告诉我们将帮助stackoverflow用户诊断问题。

You handle the file by using: 您可以使用以下方法处理文件:

$request->file('image_url');

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

Another approach is to convert img into base64 and pass it as a param. 另一种方法是将img转换为base64并将其作为参数传递。 Then in your controller/route you can decode the base64 and save to a file (if is needed). 然后,在您的控制器/路由中,您可以解码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>

and route 和路线

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM