简体   繁体   中英

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. I am trying to send an image to my api through ajax from my form in the client side, which is the web.

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

<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

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.

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.

EDIT: What happens when you click the submit button? Telling us will help stackoverflow users diagnose the problem.

You handle the file by using:

$request->file('image_url');

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

Another approach is to convert img into base64 and pass it as a param. Then in your controller/route you can decode the base64 and save to a file (if is needed).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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