首页 > 解决方案 > 在 Laravel 中使用 ajax 上传图片

问题描述

我的Laravel网站中有一个用户信息表单,并尝试使用Ajax.

<form id="edit_form" enctype="multipart/form-data">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />

<div class="form-group">
    <label>Image</label>
    <input id="edit_form_image" type="file" class="form-control" name="user_image">
</div><!-- end form-group -->

<div class="form-group">
    <label>Name</label>
    <input id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
</div><!-- end form-group -->

<button type="button" id="edit_form_submit" class="btn btn-orange">Save Changes</button>

阿贾克斯

$('#edit_form_submit').click(function(event) {

var fd = new FormData();

var edit_form_image = $('#edit_form_image')[0].files;
var edit_form_name = $('#edit_form_name').val();
var token = $('input[name=_token]').val();

fd.append( 'image', edit_form_image );
fd.append( 'name', edit_form_name );
fd.append( '_token', token );

$.ajax({

   url:"{{ url('/profile-update') }}",
   data: fd,
   async:false,
   type: 'POST',
   processData: false,
   contentType: false,
   success:function(msg)
   {
       console.log(msg);
   }
});
});

但在我的控制器中,我无法获取图像文件。

控制器

if (request()->hasFile('image'))
    {
       return "file present";
    }
    else{
        return "file not present";
    }

虽然我上传一个图像控制器总是响应“文件不存在”。

错误在哪里?有人帮忙吗?

标签: phpajaxlaravellaravel-5image-upload

解决方案


你为什么不命名你的输入标签,因为你需要在 post 方法中发送:

<input  name="image" id="edit_form_image" type="file" class="form-control">
<input name="name" id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">

和,

$("#edit_form").on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
        url:"{{ url('/profile-update') }}",
        type: "POST",
        data:  new FormData(this),
        processData: false,
        contentType: false,
        success:function(msg)
        {
            console.log(msg);
        }
   });
});

这可能有效。


推荐阅读