【问题标题】:Issue with uploading multi part image file with dio in Flutter在 Flutter 中使用 dio 上传多部分图像文件的问题
【发布时间】:2021-01-01 22:19:47
【问题描述】:

我在 Flutter 应用中使用 Dio 框架将图像上传到服务器。迪奥版本 3.0.9。 发帖方式。 添加了 4 个标题 使用图像和其他字段创建表单数据。

我分析了更多的方法。就像将 Dio 降级到 2.3.1,使用 UploadFileInfo 方法。不成功。然后使用 multipartfileupload。终于有这个了。

Future<bool> createStoreWithDio() async {
    Map<String, String> headers = {
      "Accept": "application/json",
      "authorization": tokenString,
      "authtype": "admin",
      "Content-Type": "multipart/form-data"
    };
    try {
      FormData formData = new FormData.fromMap({
        "logo": await http.MultipartFile.fromPath("logo", imageFile.path,
            contentType: new MediaType('image', 'png')),
        "name": " Bala ios",
        "description": "_description",
        "website": "www.website.com",
        "password": "Test password",
        "user_name": "Test userInformationName",
        "mobile": "9988776655",
        "email": "test@techit.io",
   
      });

      print(formData.fields);
      Response response = await dio
          .post(
        "API",
        data: formData,
        options: Options(
          headers: headers,
        ),
      )
          .then((value) {
        print(value.toString());
      });
      print(response.toString());
    } catch (error) {
      print(error);
    }
  }

imageFile 是我从相机/图库中捕获的文件。

我收到 500 异常。任何帮助都会有所帮助

【问题讨论】:

    标签: flutter dart file-upload multipartform-data dio


    【解决方案1】:

    我不确定是什么原因造成的,此代码用于我根据您的代码进行更改的应用程序中,但我没有发送任何标题,因此您需要添加然后尝试使用此代码让我知道它适用于you.also 确保您有文件 imageFile.path 并且您的 api url 是否正确 确保您已导入

    `'import  package:http_parser/http_parser.dart';
      import 'package:mime/mime.dart';`
    
     Dio dio = new Dio();
          final mimeTypeData =
          lookupMimeType(imageFile.path, headerBytes: [0xFF, 0xD8]).split('/');
          FormData formData = FormData.fromMap({
            "name": " Bala ios",
            "description": "_description",
            "website": "www.website.com",
            "password": "Test password",
            "user_name": "Test userInformationName",
            "mobile": "9988776655",
            "email": "test@techit.io",
            "logo": await MultipartFile.fromFile(imageFile.path,
                contentType: MediaType(mimeTypeData[0], mimeTypeData[1])),
          });
    
          var response = await dio.post(
            Urls.ImageInsert,
            data: formData,
          );
    
          var message = response.data['message'];
    

    【讨论】:

    • 感谢您的回复,我仍然收到 500 异常
    • 未处理异常:DioError [DioErrorType.RESPONSE]:Http 状态错误 [500]
    • 服务器不喜欢某些东西并返回状态码500,这通常表示“服务器错误”,可能是标头值有问题,您是否尝试使用此API通过邮递员上传数据, @钱德鲁
    • 你可以在不发送任何标题的情况下上传数据吗?你必须更改 test@chandru 的 API
    猜你喜欢
    • 1970-01-01
    • 2020-08-02
    • 2020-10-20
    • 2013-10-12
    • 1970-01-01
    • 2020-05-03
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多