DD($请求 - >所有()); 给出空数组

chl*_*lee 14 php laravel

我正在尝试从我的Laravel 5应用程序上传照片以存储在AWS中.我正在使用Postman REST客户端进行测试.当我上传照片时,请求返回一个空数组.有谁知道为什么会这样?这是我的头像控制器的代码:

class AvatarController extends Controller
{

  public function __construct(AWS $aws)
  {
      $this->aws = $aws;
  }

/**
 * Store a new avatar for a user.
 * POST northstar.com/users/{id}/avatar
 */
  public function store(User $user, Request $request)
  {
    dd($request->all());
    // dd($request->file('photo'));

    $file = $request->file('photo');
    // $file = Request::file('photo');
    // $file = Input::file('photo');

    $v = Validator::make(
      $request->all(),
      ['photo' => 'required|image|mimes:jpeg,jpg|max:8000']
    );

    if($v->fails())
      return Response::json(['error' => $v->errors()]);         

    $filename = $this->aws->storeImage('avatars', $file);

    // Save filename to User model
    $user->avatar = $filename;
    $user->save();

    // Respond to user with success
    return response()->json('Photo uploaded!', 200);
  }
}
Run Code Online (Sandbox Code Playgroud)

chl*_*lee 21

找到了答案 - 看起来Postman中的标题存在问题.我有Accept application/json和Content-Type application/json.删除Content-Type后,所有内容都已修复.谢谢!

  • @HosMercury,如果打开Postman,并且在URL下应该看到四个选项卡-授权,标头,正文,请求前脚本和测试。单击标题选项卡,您应该能够输入上面的内容!“ Accept”在同一行的左列和右列中,您将在“ Content-Type”中写上“ application / json”,并在下一行中写上“ application / json”。希望这可以帮助! (2认同)

Hos*_*ari 8

直接使用 PUT/PATCH 方法时,邮递员也会遇到同样的问题。一种可能的解决方案是将 PUT/PATCH 请求作为 POST发送,但在请求正文中包含正确的_method以及其他参数。

_method: PUT

希望这可以帮助


use*_*546 7

参加聚会有点晚了,但可能对其他人有用:我的问题是Content-Type标头值是application/json,而实际有效负载是表单数据。更改标题以application/x-www-form-urlencoded解决问题。


小智 6

只是想补充一下我犯错误的地方。使用Postman发送POST请求时,还必须确保json是正确的。

// invalid json (notice the ending comma)
{
    "akey":"aval",
    "nkey": "bval",
}

//valid json (no ending comma)
{
    "akey":"aval",
    "nkey": "bval"
}
Run Code Online (Sandbox Code Playgroud)