LARAVEL 5使用AJAX将图像发送到控制器

时间:2016-01-28 19:21:53

标签: ajax image file laravel

当我想通过Ajax将图像传递给控制器​​时,我遇到了一些问题。任何帮助?这是我的代码

// ROUTE

Route::post('get-image', 'CreateImageController@get_image');

// IMAGE.BLADE.PHP

{!! Form::open([ 'id'=>'upload-doc','files'=>true ]) !!}

{!! Form::file('fileupload', ['id'=>'fileupload', 'onchange'=>"this.parentNode.nextSibling.value = this.value" ], null) !!}Browse
<button type="button" id="uploadFile">Upload</button>
{!! Form::close() !!}

// AJAX

action  = "<?php echo action('CreateImageController@get_image'); ?>";
$.ajax({
    url:    action,
    type:   'POST',
    data:   new FormData($("#upload_doc")[0]),
    cache:  false,
    dataType: 'json',
    processData: false,
    contentType: false, 
    success: function(data){
        alert(data.display);
    }
});

// CONTROLLER函数get_image()

public function get_image(){

        $name = '';
        $image = \Input::file('fileupload');
        $validator = \Validator::make([$image], ['image' => 'required']);
        if ($validator->fails()) {
            $name = "FAIL";
        }
        else{
            $name = "SUCCESS";
        }

        $data = array('display' => $name);
        echo json_encode($data);
  }

我每次得到的结果都是&#34;失败&#34;。我做错了什么?

3 个答案:

答案 0 :(得分:0)

你可以做到

if (Input::file('fileupload')) {

}

作为一种验证方式。

答案 1 :(得分:0)

@ SAri Yono,我通过之后没有任何观点;它被发送回ajax jquery以使用alert / console.log显示结果

<meta name="_token" content="{{ csrf_token() }}" /> 
<script type="text/javascript">

$(document).ready(function() {  

$("#upload-doc").submit(function(e){
    e.preventDefault();
});

$.ajaxSetup({
 headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')    }
}); 

$.ajax({
   url:     action,
   type:    'POST',
   data:    new FormData($("#upload_doc")[0]),
   cache:   false,
   dataType: 'json',
   processData: false,
   contentType: false, 
   success: function(data){
        console.log(display);
   }
});

e.preventDefault();

});
</script>

在body标签之间我只有Form。

{!! Form::open([ 'id'=>'upload-doc','files'=>true ]) !!}
{!! Form::file('fileupload', ['id'=>'fileupload'], null) !!}
<button type="button" id="uploadFile">Upload</button>
{!! Form::close() !!}

Console.log显示此Object {display: "FAIL"}

答案 2 :(得分:0)

我解决了。因为我在提交表单时只收到文件。我决定添加

$("#upload-doc").submit();  
var formData = new FormData($('#upload-doc')[0]);

在我的jquery方法中

$("#uploadFile").click(function(e) {

$("#upload-doc").submit();
var formData = new FormData($('#upload-doc')[0]);
action="<?php echo action('CreateImageController@get_image'); ?>";

$.ajax({
    url:    action,
    type:   'POST',
    data:   formData,
    cache:  false,
    dataType: 'json',
    processData: false,
    contentType: false, 
    success: function(data){
        alert('in success');
        console.log(data);
        e.preventDefault();
    }
});
})