0

我想通过dio包以jpg格式将图像发送到服务器,我该怎么做?

选择图像方法:

  void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
  file = file;
  print(file);
});

上传图片方法:

  void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
  "image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
  print(json.decode(onValue));
});

有人帮我吗?

谢谢

4

2 回答 2

0

您也可以为此目的使用 http

Future<String> uploadImage(Asset asset,String orderId) async {

  // String to uri
  Uri uri = Uri.parse('Your URL');

  // create multipart request
  http.MultipartRequest request = http.MultipartRequest("POST", uri);

  ByteData byteData = await asset.getByteData();
  List<int> imageData = byteData.buffer.asUint8List();



  http.MultipartFile multipartFile =  http.MultipartFile.fromBytes(
   'image',
   imageData,
   filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
   contentType: MediaType("image", "jpg"),
  );

  // Add field to your request
  request.fields['FieldName'] = fieldValue;

  // add file to multipart
  request.files.add(multipartFile);
  // send
  var response = await request.send();

  // Decode response
  final respStr = await response.stream.bytesToString();

  return respStr;

}

于 2020-02-20T13:20:34.007 回答
0

请试试这个

       Future<dynamic> _upload() async {
            if (file == null) return;
            String fileName = file.path.split('/').last;
            Map<String, dynamic> formData = {
              "image": await MultipartFile.fromFile(file.path,filename: fileName),
            };
           return await Dio()
        .post(url,data:formData).
    then((dynamic result){
    print(result.toString());
});
}
于 2020-02-20T13:08:44.580 回答