【问题标题】:laravel image upload - ajax do not post my image filelaravel 图片上传 - ajax 不发布我的图片文件
【发布时间】:2015-06-25 12:30:39
【问题描述】:

我正在尝试将 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

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

【问题讨论】:

  • 你最好使用jQuery-File-Upload
  • 看起来很有趣,也许我的下一个功能需要这个......但由于 K.Toress 回答成功了,现在,我推迟了该库的实现。感谢您和所有 SO 社区!

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


【解决方案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;
});

【讨论】:

  • 为什么你会写$(this)[0] 而不仅仅是this
猜你喜欢
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 2019-02-06
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
相关资源
最近更新 更多