laravel图片上传 - ajax不发布我的图片文件

时间:2015-04-18 16:21:05

标签: php ajax laravel image-upload multipartform-data

我正在尝试将ajax调用的图像上传到我的服务器(在laravel上)。

这是我的服务器代码:

if (Input::hasFile('flyer')){
    Log::info('WORK!');
    $file = Input::file('flyer');
    $file->move('uploads', $file->getClientOriginalName());
}

正如你所看到的,我已经设置了一个日志构造来了解我的文件是否被上传......但是我的日志文件说它不是......

我的表单代码:

{{ Form::open(array('url' => 'new_event', 'id' => 'newEvent', 'files' => true)) }}
    //some fields...
    {{ Form::file('flyer', array('class' => 'form-control', 'id'=>'inputImage')) }}
    // some other fields
{{ Form::close() }}

这是我的ajax电话:

$('#newEvent').submit(function() {
    $.ajax({
        data: $(this).serialize(),
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        success: function(response) {
            $('#content').html(response);
        }
    });
    return false;
});

当我发布表单时,最后是我的后期数据(来自谷歌开发者控制台):

_token:bqyiuQwtYEEs0tvhBcndi4ylsVPPi2FpYhGPLxKQ
title:sdfgsdf
description:sdfgsdf
activated_at:23/04/2015
expire_on:24/04/2015
contact:a name
phone:+387646
email:some@one.com
push:1

正如您所看到的,我的图像文件(传单)没有任何痕迹......为什么?

1 个答案:

答案 0 :(得分:1)

您无法提交此类图片,需要enctype="multipart/form-data",请尝试以下代码。

$('#newEvent').submit(function() {

    // need to get form data as below
    var formData = new FormData($(this)[0]);

    $.ajax({
        data: formData,
        contentType: false,
        processData: false,
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        success: function(response) {
            $('#content').html(response);
        }
    });
    return false;
});