Flutter Laravel:使用Dio和ImagePicker上传图像

时间:2020-09-09 09:18:58

标签: php laravel flutter dart dio

当Postman中的请求返回成功响应时,我无法使用Dio和ImagePicker从Flutter将图像上传到我的Laravel服务器

邮递员: postman_screenshot

Laravel:

public function uploadFile(Request $request) {
        if($request->hasFile('image')) {
            $name = time()."_".$request->file('image')->getClientOriginalName();
            $request->file('image')->move(public_path('images'), $name);
        }
        return response()->json([
            asset("images/$name"),
            201,
            'message' => asset("images/$name") ? 'Image saved' : 'Image failed to save'
        ]);
    }

颤振:

Future getImage(context) async {
    var image = await picker.getImage(
        source: ImageSource.gallery,
        imageQuality: 50,
        maxHeight: 500.0,
        maxWidth: 500.0);
    imageFile = File(image.path);
    _uploadFile(imageFile);
  }

  _uploadFile(File file) async {
    String name = file.path.split('/').last;
    var data = FormData.fromMap({
      "name": await MultipartFile.fromFile(
        file.path,
        filename: name,
      ),
    });

    Dio dio = new Dio();
    await dio
        .post("http://localhost:8000/api/upload-file", data: data)
        .then((response) => print(response))
        .catchError((error) => print(error));
  }

服务器端错误:Http status error [500] Undefined variable *name* in file ...

2 个答案:

答案 0 :(得分:0)

更改以下代码后,您会再试一次吗?

 var data = FormData.fromMap({
      "image": await MultipartFile.fromFile(
        file.path,
        filename: name,
      ),
    });

答案 1 :(得分:0)

请试试这个,它对我有用:

List<MultipartFile> multiFiles = [];
for(int i = 0; i < files.length; i++) {
multiFiles.add(await MultipartFile.fromPath('profile_photo[]', files[i].path));
}
request.files.addAll(multiFiles);