如何使用http上传图片?

时间:2019-07-12 11:13:18

标签: http flutter dart

我正在尝试使用Flutter的http插件上传图像。

以下是我的代码

Future<ImageUploadModel> postImage(File photoPath) async {
    ImageUploadModel imageUploadModel;

    var request = http.MultipartRequest(
        "POST", Uri.parse("my_api_url"));

    request.files.add(http.MultipartFile.fromBytes(
        "photo", await File.fromUri(Uri.parse(photoPath.path)).readAsBytes(),
        contentType: MediaType('image', 'jpg')));

    final response = await request.send();

    Uint8List responseByteArray = await response.stream.toBytes();

return standardSerializers.deserializeWith(ImageUploadModel.serializer, json.decode(utf8.decode(responseByteArray)));
  }

我尝试使用Postman上传图片,并且图片正确上传。

我已跟踪堆栈上的链接,但无法解决错误

Flutter: http post upload an image Flutter how to send multiple files to http post How to send an image to an api in dart/flutter? How to upload image in Flutter?

我得到的状态码为200,但是当我尝试从响应中访问任何变量时,我得到的是空字符串。

我尝试使用Kotlin和Retrofit在本机Android上正常运行

我还尝试了Dio

Dio dio = Dio();
    FormData formdata = FormData();

    formdata.add("photo", UploadFileInfo(photoPath, basename(photoPath.path)));
    dio
        .post("My_API_URL",
            data: formdata,
            options: Options(
                method: 'POST',
                responseType: ResponseType.json // or ResponseType.JSON
                ))
        .then((response) {
      print("2 $response");
      return standardSerializers.deserializeWith(
          ImageUploadModel.serializer, json.decode(response.data));
    }).catchError((error) => print("3 $error"));

我不想将图像转换为base64

2 个答案:

答案 0 :(得分:1)

响应是流,因此是异步的。您要先返回imageUploadModel,然后才能为其分配一个值。尝试以下代码:

Uint8List responseByteArray = await response.stream.toBytes();

return standardSerializers.deserializeWith(ImageUploadModel.serializer, json.decode(utf8.decode(responseByteArray)));

答案 1 :(得分:0)

我终于明白了。以下代码对我有用。

var request = http.MultipartRequest(
        "POST", Uri.parse("MY_API_URL"));
    var multipartFile = await http.MultipartFile.fromPath(
        "photo", photoPath.path,
        contentType: MediaType('image', 'jpeg'));
    request.files.add(multipartFile);
    http.StreamedResponse response = await request.send();
    var responseByteArray = await response.stream.toBytes();

    return ImageUploadModel.fromJson(
        json.decode(utf8.decode(responseByteArray)));

只需根据您的要求更改MediaType