Flutter DIO: upload image using binary body with Dio package

百般思念 提交于 2021-01-27 21:43:35

问题


With thwe http package I can send an image to a server by putting te binary data in the body of a post call like in the snippet of this code:

var response = await http.post('My_url', body: File(path).readAsBytesSync(),  headers: {
                    'apikey': 'myAPIKEY',
                    'Content-Type': 'image/*', // set content-length
                  });

I can't do the same thing by using Dio, I don't know how to put directly the binary data in the body (like i can do it with postman)


回答1:


Just putting my solution if someone stumbles upon the same issue.

I had to upload the file at a signed google storage URL. API required to insert the file binary data in the body of the PUT request. Couldn't implement using the DIO plugin, I resolved the issue using the DART HTTP package, Below is a sample code.

import 'package:http/http.dart' as http;

await http.put(
  Uri.parse(uploadURL),
  headers: {
    'Content-Type': mimeType,
    'Accept': "*/*",
    'Content-Length': File(filePath).lengthSync().toString(),
    'Connection': 'keep-alive',
  },
  body: File(filePath).readAsBytesSync(),
);



回答2:


I kept getting http 403 when using dio package to upload binary data to google storage api. I was able to fix this using :

      Response responseGoogleStorage = await dio.put(
      googleStorage.url,
      data: File(_imageFile.path).readAsBytesSync(),
      options: Options(
        headers: {
          'Content-Type': contentType,
          'Accept': "*/*",
          'Content-Length': File(_imageFile.path).lengthSync().toString(),
          'Connection': 'keep-alive',
        },
      ),
    );



回答3:


I have declared a FormData object named 'data' and have a map of image with key as filename and value as filepath. 'image' is the key defined on the server side.

 data.files.add(MapEntry(
    'image',
      await MultipartFile.fromFile(image.values.first, filename: "${image.values.first.split("/").last}")
                                ));


来源:https://stackoverflow.com/questions/62648883/flutter-dio-upload-image-using-binary-body-with-dio-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!