0

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

邮递员: postman_screenshot

拉拉维尔:

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 ...

4

2 回答 2

1

你会在用下面的代码改变之后再试一次吗?

 var data = FormData.fromMap({
      "image": await MultipartFile.fromFile(
        file.path,
        filename: name,
      ),
    });
于 2020-09-09T09:29:31.757 回答
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);
于 2021-04-07T18:21:50.650 回答