首页 > 解决方案 > Flutter 和 Laravel API。上传文件。此路由不支持 GET 方法。支持的方法:POST

问题描述

我想从 Flutter 上传图片。但我收到此错误:

此路由不支持 GET 方法。支持的方法:POST。

但是我将我的 api 路由设置为POST方法。而且我也发送POST方法请求,但我仍然收到此错误。

但还有一件事,它适用于POSTMANand INSOMNIA。没有问题。

在此处输入图像描述

我用这个header

Content-Type: multipart/form-data
Authorization: ....

请帮我。

我的路线是:

Route::post('/avatar/update', 'Api\ProfileController@avatar_update')->name('api.avatar.update');

我的控制器:

public function avatar_update(Request $request){
        $request->validate(array(
            'avatar' => 'required|image',
        ));
        try{
            $image = Image::make($request->avatar)->fit(250, 250);
            $photo_name = Auth::user()->username."-".strtotime(now()).'.'.$request->avatar->extension();
            $path='images/avatars/'.$photo_name;
            $image->save($path);

            if(File::exists(Auth::user()->avatar)) {
                File::delete(Auth::user()->avatar);
            }

            Auth::user()->update([
                'avatar' => 'http://attendance.isadma.com/'.$path,
            ]);
            return response()->json([
                'status' => 1,
                'message' => 'Picture updated.',
                'image' => Auth::user()->avatar
            ], 200);
        }
        catch (\Exception $e){
            return response()->json([
                'status' => 0,
                'message' => $e->getMessage()
            ], 500);
        }
    }

颤振请求代码:

@override
  Future<String> uploadProfilePic(File profilePic, String token) async {
    var postUri = Uri.parse("$url/avatar/update");
    print(profilePic.path);
    print(postUri);
    var request = http.MultipartRequest("POST", postUri);
    request.headers['authorization'] = "Bearer $token";
    request.headers['Content-Type'] = "multipart/form-data";

    request.files.add(
      await http.MultipartFile.fromPath(
        'avatar',
        profilePic.path,
        contentType: MediaType('image', 'jpg'),
        filename: basename(profilePic.path),
      ),
    );

    print(request.headers);

    request.send().then((res) async {
      print(res.headers);
      print(res.statusCode);
      print(await res.stream.bytesToString());
    }).catchError((e) {
      print(e);
    });
  }

标签: laravelapiflutterlaravel-6.2

解决方案


确保您在发布请求中发送 csrf 数据 (_token)


推荐阅读