dtj4307 2017-01-19 12:03
浏览 48

图像上传Laravel 5.3使用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

  • 写回答

3条回答 默认 最新

  • duancan1900 2017-01-19 12:16
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致