Php 使用AJAX时,Laravel 5文件上载不起作用

Php 使用AJAX时,Laravel 5文件上载不起作用,php,ajax,laravel,laravel-5,image-uploading,Php,Ajax,Laravel,Laravel 5,Image Uploading,我以前在处理Laravel时从未遇到过这个问题 我有一个表格,将插入产品的详细信息,其中也有一个图像字段 以下是我如何创建用于插入产品详细信息的视图: {!! Form::open(['url' => '/admin/products', 'autocomplete' => 'off', 'id' => 'formAddProduct', 'files' => true]) !!} <div class="errors"></div>

我以前在处理Laravel时从未遇到过这个问题

我有一个表格,将插入产品的详细信息,其中也有一个图像字段

以下是我如何创建用于插入产品详细信息的视图:

{!! Form::open(['url' => '/admin/products', 'autocomplete' => 'off', 'id' => 'formAddProduct', 'files' => true]) !!}
    <div class="errors"></div>

    @include('admin.products.form', ['submitButtonText' => 'Add Product', 'submitButtonId' => 'btnAddProduct'])
{!! Form::close() !!}
还有ajax:

$('#btnAddProduct').on('click', function() {
    var inputData = $('#formAddProduct').serialize();

    $.ajax({
        url: '{{ url('/admin/products') }}',
        type: 'POST',
        data: inputData,
        success: function( message ) {
            alert( message.msg );
            if ( message.status === 'success' ) {
                toastr.success('Product added successfully.');
                toastr.options.closeButton = true;
                toastr.options.showMethod = "slideDown";
                toastr.options.hideMethod = "slideUp";

                $('input').val( '' );
                $('select').val( '' );
            }
        },
        error: function( data ) {
            if ( data.status === 422 ) {
                var errors = data.responseJSON;
                var errorsHtml = '<div class="alert alert-danger"><ul>';
                errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
                $.each( errors, function( key, value ) {
                    errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
                });
                errorsHtml += '</ul></div>';

                $( '.errors' ).html( errorsHtml );
            }
        }
    });

    return false;
});
$('btnAddProduct')。在('click',function()上{
var inputData=$('#formAddProduct').serialize();
$.ajax({
url:“{url('/admin/products')}}”,
键入:“POST”,
数据:输入数据,
成功:功能(消息){
警报(message.msg);
如果(message.status==='success'){
toastr.success('产品添加成功');
toastr.options.closeButton=true;
toastr.options.showMethod=“slideDown”;
toastr.options.hideMethod=“slideUp”;
$('input').val('');
$('select').val('');
}
},
错误:函数(数据){
如果(data.status==422){
var errors=data.responseJSON;
var errorsHtml='
    '; errorsHtml+='×;'; $.each(错误、函数(键、值){ errorsHtml+='
  • '+值[0]+'
  • ';//仅显示第一个错误。 }); errorsHtml+='
'; $('.errors').html(errorsHtml); } } }); 返回false; });
我得到的错误是
没有文件

当我执行
var_dump($request->file('image_file'))时我在chrome的响应选项卡中获得
null

当我执行
var_dump(输入::文件('image_文件'))时我在chrome的响应选项卡中获得
null

我哪里出错了?请帮帮我。谢谢

p.S.:我使用了
干预
作为图像上载功能。

serialize()方法不发送文件信息供远程处理程序处理。另一种选择是使用。 有关示例,请参见此链接:

注意:在jQuery ajax请求中将processData和contentType设置为false很重要,否则在jQuery尝试处理它时会导致错误。

serialize()方法不会发送文件信息供远程处理程序处理。另一种选择是使用。 有关示例,请参见此链接:


注意:在jQuery ajax请求中将processData和contentType设置为false很重要,否则在jQuery尝试处理它时会导致错误。

您应该在ajax调用中添加
data:formData,
async:false,

因此,您的ajax将是

$("form[name='yourformname']").submit(function(e) {//If you use form submit then have your form name here
//$('#btnAddProduct').on('click', function() {
var inputData = new FormData($(this)[0]);
//var inputData = $('#formAddProduct').serialize(); not matter :p
  e.preventDefault();
$.ajax({
    url: '{{ url('/admin/products') }}',
    type: 'POST',
    data: inputData,
    async: false,
    success: function( message ) {
        alert( message.msg );
        if ( message.status === 'success' ) {
            toastr.success('Product added successfully.');
            toastr.options.closeButton = true;
            toastr.options.showMethod = "slideDown";
            toastr.options.hideMethod = "slideUp";

            $('input').val( '' );
            $('select').val( '' );
        }
    },
    error: function( data ) {
        if ( data.status === 422 ) {
            var errors = data.responseJSON;
            var errorsHtml = '<div class="alert alert-danger"><ul>';
            errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
            $.each( errors, function( key, value ) {
                errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
            });
            errorsHtml += '</ul></div>';

            $( '.errors' ).html( errorsHtml );
        }
    }
});

return false;
});
$(“form[name='yourformname'])。submit(函数(e){//如果使用form submit,请在此处输入表单名称
//$('btnAddProduct')。在('click',function()上{
var inputData=newformdata($(this)[0]);
//var inputData=$(“#formAddProduct”).serialize();无所谓:p
e、 预防默认值();
$.ajax({
url:“{url('/admin/products')}}”,
键入:“POST”,
数据:输入数据,
async:false,
成功:功能(消息){
警报(message.msg);
如果(message.status==='success'){
toastr.success('产品添加成功');
toastr.options.closeButton=true;
toastr.options.showMethod=“slideDown”;
toastr.options.hideMethod=“slideUp”;
$('input').val('');
$('select').val('');
}
},
错误:函数(数据){
如果(data.status==422){
var errors=data.responseJSON;
var errorsHtml='
    '; errorsHtml+='×;'; $.each(错误、函数(键、值){ errorsHtml+='
  • '+值[0]+'
  • ';//仅显示第一个错误。 }); errorsHtml+='
'; $('.errors').html(errorsHtml); } } }); 返回false; });
更新:

  • 在ajax调用中启用
    async:true

  • 在您的Laravel验证器规则
    image\u文件'=>'mimes:jpeg,jpg,jpg'


  • 您应该在ajax调用中添加
    data:formData、
    async:false、

    因此,您的ajax将是

    $("form[name='yourformname']").submit(function(e) {//If you use form submit then have your form name here
    //$('#btnAddProduct').on('click', function() {
    var inputData = new FormData($(this)[0]);
    //var inputData = $('#formAddProduct').serialize(); not matter :p
      e.preventDefault();
    $.ajax({
        url: '{{ url('/admin/products') }}',
        type: 'POST',
        data: inputData,
        async: false,
        success: function( message ) {
            alert( message.msg );
            if ( message.status === 'success' ) {
                toastr.success('Product added successfully.');
                toastr.options.closeButton = true;
                toastr.options.showMethod = "slideDown";
                toastr.options.hideMethod = "slideUp";
    
                $('input').val( '' );
                $('select').val( '' );
            }
        },
        error: function( data ) {
            if ( data.status === 422 ) {
                var errors = data.responseJSON;
                var errorsHtml = '<div class="alert alert-danger"><ul>';
                errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
                $.each( errors, function( key, value ) {
                    errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
                });
                errorsHtml += '</ul></div>';
    
                $( '.errors' ).html( errorsHtml );
            }
        }
    });
    
    return false;
    });
    
    $(“form[name='yourformname'])。submit(函数(e){//如果使用form submit,请在此处输入表单名称
    //$('btnAddProduct')。在('click',function()上{
    var inputData=newformdata($(this)[0]);
    //var inputData=$(“#formAddProduct”).serialize();无所谓:p
    e、 预防默认值();
    $.ajax({
    url:“{url('/admin/products')}}”,
    键入:“POST”,
    数据:输入数据,
    async:false,
    成功:功能(消息){
    警报(message.msg);
    如果(message.status==='success'){
    toastr.success('产品添加成功');
    toastr.options.closeButton=true;
    toastr.options.showMethod=“slideDown”;
    toastr.options.hideMethod=“slideUp”;
    $('input').val('');
    $('select').val('');
    }
    },
    错误:函数(数据){
    如果(data.status==422){
    var errors=data.responseJSON;
    var errorsHtml='
      '; errorsHtml+='×;'; $.each(错误、函数(键、值){ errorsHtml+='
    • '+值[0]+'
    • ';//仅显示第一个错误。 }); errorsHtml+='
    '; $('.errors').html(errorsHtml); } } }); 返回false; });
    更新:

  • 在ajax调用中启用
    async:true

  • 在您的Laravel验证器规则
    image\u文件'=>'mimes:jpeg,jpg,jpg'


  • 在发出包含包装在formData对象中的文件的Ajax请求之前,您需要了解一些陷阱和技术

  • 制造
    $("form[name='yourformname']").submit(function(e) {//If you use form submit then have your form name here
    //$('#btnAddProduct').on('click', function() {
    var inputData = new FormData($(this)[0]);
    //var inputData = $('#formAddProduct').serialize(); not matter :p
      e.preventDefault();
    $.ajax({
        url: '{{ url('/admin/products') }}',
        type: 'POST',
        data: inputData,
        async: false,
        success: function( message ) {
            alert( message.msg );
            if ( message.status === 'success' ) {
                toastr.success('Product added successfully.');
                toastr.options.closeButton = true;
                toastr.options.showMethod = "slideDown";
                toastr.options.hideMethod = "slideUp";
    
                $('input').val( '' );
                $('select').val( '' );
            }
        },
        error: function( data ) {
            if ( data.status === 422 ) {
                var errors = data.responseJSON;
                var errorsHtml = '<div class="alert alert-danger"><ul>';
                errorsHtml += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>';
                $.each( errors, function( key, value ) {
                    errorsHtml += '<li>' + value[0] + '</li>'; //showing only the first error.
                });
                errorsHtml += '</ul></div>';
    
                $( '.errors' ).html( errorsHtml );
            }
        }
    });
    
    return false;
    });