我正在尝试从我的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);
}
}
答案 0 :(得分:16)
找到答案 - 看起来Postman中的标题存在问题。我有Accept application / json和Content-Type application / json。删除Content-Type后,所有内容都已修复。谢谢!
答案 1 :(得分:4)
只想添加我犯错的地方。 通过Postman发送POST请求时,还必须确保json正确。
// invalid json (notice the ending comma)
{
"akey":"aval",
"nkey": "bval",
}
//valid json (no ending comma)
{
"akey":"aval",
"nkey": "bval"
}
答案 2 :(得分:1)
晚点参加聚会,但对其他人可能有用:
我的问题是,Content-Type
标头值为application/json
,而实际有效载荷是表单数据。将标题更改为application/x-www-form-urlencoded
可以解决此问题。
答案 3 :(得分:1)
直接使用PUT / PATCH方法时,邮递员也遇到同样的问题。 一种可能的解决方案是将您的PUT / PATCH请求作为POST 发送,但在请求正文中包含正确的 _method 以及其他参数。
_method: PUT
希望这会有所帮助
答案 4 :(得分:0)
尝试使用此
dd($request->all());
答案 5 :(得分:0)
尝试dd($ request),dd($ _ REQUEST),dd($ request-> files)。
答案 6 :(得分:0)
您可能想测试JSON是否有效
$data = $request->all();
if(empty($data)) {
$data = json_decode($request->getContent());
$data = json_decode($data);
if(is_null($data)) {
return response()->json("Not valid json", 400);
}
}
答案 7 :(得分:-1)
只需更改您的Rout文件
Route::get('/users', 'AvatarController@store');
到
Route::POST('/users', 'AvatarController@store');
答案 8 :(得分:-5)