解决ajax异步上传文件的问题

HTML:
<form id=" avater" name=" formlist">
{{ csrf_field() }}
<ul class="list-group container" style="width:50%">
    <li class="list-group-item list" style="border-radius: 5px">
        <input id=" image" class="file" type="file" name=" file">
        <button id=" btn" style=" width: 50px;height: 25px;padding:0" class="btn btn-primary radius" type="button">上传</button>
    </li>
</ul>
</form>
Jquery:
$('#btn').on('click', function() {
    var file = $('#image')[0].files[0];
    var form = $('#avater')[0];
    var formdata = new FormData(form);
    formdata.append('image', file)
   $.ajax({
       type: 'post',
       url: "{{url('setava')}}",
       data: formdata,
       dataType: 'json',
       processData: false,
       contentType: false,
       success: function(res) {
            if (res.status == 0) {
                 alert(res.msg);
                 window.location.href = "{{url('set')}}";
            }
      }
});
红色部分为重要部分,使用FormData对象可以解决ajax异步上传文件的问题。并且可以同时传输表单内容和文件的合并上传,后台代码正常接值就可以。(文件时用file来接)

猜你喜欢

转载自www.cnblogs.com/CWJDD/p/11456883.html
今日推荐