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

问题描述

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

解决方法

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

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

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

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);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...