【问题标题】:Request object is empty in a lumen api流明 api 中的请求对象为空
【发布时间】:2018-01-10 00:43:31
【问题描述】:

通过ajax调用在lumen API中上传图片文件,没有拿到lumen中的图片进行处理,Request对象为空。

Ajax 调用

var file = $('#img')[0].files[0];
var form_data = new FormData(document.getElementById("myform"));
form_data.append("img", file);

$.ajax({
    url: "http://localhost:8000/api/image",
    type: "POST",
    data: form_data,
    enctype: 'multipart/form-data',
    processData: false, // tell jQuery not to process the data
    contentType: false   // tell jQuery not to set contentType
})
.done(function (data) {
    console.log(data);
});

路线

$api->post('/image', 'ImagesController@addImage');

控制器

public function addImage(Request $request) {
    return $request; // returns empty object
}

Request payload

Response

【问题讨论】:

  • 你解决了这个问题吗?

标签: php ajax laravel api lumen


【解决方案1】:

您可以通过这种方式构建 JavaScript 对象,这将确保将主体传递给请求。

let form_data = {
      'name': $('#name').value(),
      'file': $('#img')[0].files[0]
    };

    $.ajax({
      url: "http://localhost:8000/api/image",
      type: "POST",
      data: form_data,
      enctype: 'multipart/form-data',
      processData: false, // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    })
    .done(function (data) {
      console.log(data);
    });

【讨论】:

    【解决方案2】:

    在你的控制器中添加这一行

    use Illuminate\Http\Request;
    

    不要使用 Request 外观,因为 Lumen 与 Laravel 的工作方式不同。

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 2020-08-22
      • 2018-12-28
      • 2018-01-06
      • 2021-12-04
      相关资源
      最近更新 更多