dart 使用Flutter和Dio将图像上传到API

50pmv0ei  于 2023-07-31  发布在  Flutter
关注(0)|答案(2)|浏览(206)

如何将图片以字符串格式发送给API?这是在MultipartFile示例中发送数据但data['avatar']接受字符串的代码。那我该怎么做呢?请帮我拿这个。

static Future<Response> updateUserAccount({
    XFile? avatar,
    String? fullName,
    String? email,
    String? oldPhone,
    String? phone,
    String? city,
    String? streetName,
    String? landmark,
    String? oldPassword,
    String? password,
  }) async {
    final dio = Dio();
    String token = await SecureStorageUtils.getToken();
    dio.options.headers['accept'] = '*/*';
    dio.options.headers['content-type'] = 'multipart/form-data';
    dio.options.headers['authorization'] = 'Bearer $token';
    Map<String, dynamic> data = {};
    if (avatar != null) {
      data['avatar'] = await MultipartFile.fromFile(avatar.path);
    }

    if (email != null) {
      data['email'] = email;
    }

    if (oldPhone != null) {
      data['old_phone_number'] = oldPhone;
    }

    if (phone != null) {
      data['phone_number'] = phone;
    }

    if (city != null || streetName != null || landmark != null) {
      final address = {};

      if (city != null) {
        address['city'] = city;
      }

      if (streetName != null) {
        address['street_name'] = streetName;
      }

      if (landmark != null) {
        address['landmark'] = landmark;
      }
      data['address'] = address;
    }

    if (oldPassword != null) {
      data['old_password'] = oldPassword;
    }
    if (password != null) {
      data['password'] = password;
    }
    if (fullName != null) {
      data['full_name'] = fullName;
    }
    print("data: $data");

    FormData formData = FormData.fromMap(data);

    final response = await dio.patch(
      AppUrl.currentUser,
      data: formData,
    );
    return response;
  }

字符串
我试过使用base64Encoding的方法,但它没有工作。

List<int> fileBytes = await avatar.readAsBytes();
  String base64Avatar = base64Encode(fileBytes);
  data['avatar'] = base64Avatar;

wfsdck30

wfsdck301#

在我的情况是,我可以发送JSON数据,因为数据是字符串文件,所以我创建了一个类,创建base64,例如。

class ToImageData {
  static String imagetoData(String? imagepath) {
    final extension = path.extension(
      imagepath!.substring(imagepath.lastIndexOf("/")).replaceAll("/", ""),
    );
    final bytes = File(imagepath).readAsBytesSync();
    String base64 =
        "data:image/${extension.replaceAll(".", "")};base64,${base64Encode(bytes)}";
    return base64;
  }
}

字符串
因此,每当我必须用JSON发送文件时,我会这样调用它

// Lets make an example
 final data = {
     "avatar": ToImageData.imagetoData(file.path);
     // result is like this data:image/png;base64,TEWUFDBSJWEH1232347GHSD
    //something long text
 }

final response = await dio.patch(
      AppUrl.currentUser,
      data: data ,
    );
    return response;


我希望这对你有帮助。

yks3o0rb

yks3o0rb2#

为此,我使用了image_pickerimage
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker. dart';

File? _image; //Your image-file variable

_image = File(pickedFile.path); //Once user picked image file.

//Upload to API

 var fileName;
 if (_image != null) {
    fileName = _image!.path.split('/').last;
  }
 final capturedImage = img.decodeImage(await _image!.readAsBytes())!;
    final orientedImage = img.bakeOrientation(capturedImage);
    final thumbnail = img.copyResize(orientedImage, width: 200);
    await _image!.writeAsBytes(img.encodeJpg(thumbnail)).then((value) async {
     'avatar':
            await MultipartFile.fromFile(_image!.path, filename: fileName)
      _callSaveProfileApi(formData);
    });

字符串

相关问题