uploadImage method

Future<UploadJsonResult> uploadImage(
  1. String? filePath
)

Implementation

Future<UploadJsonResult> uploadImage(String? filePath) async {
  //
  String? fileName = filePath!.split("/").last;
  // 检测是否含有后缀,如果没有后缀,则添加 .png后缀
  if (!fileName.contains(".")) {
    fileName += '.png';
  }
  String? username = SpUtil.getString(BytedeskConstants.uid);

  const uploadUrl =
      '${BytedeskConstants.httpUploadUrl}/visitor/api/upload/image';
  BytedeskUtils.printLog(
      "uploadImage fileName $fileName, username $username, upload Url $uploadUrl");

  // web browser 浏览器中不支持此种上传图片方式
  // Unsupported operation: MultipartFile is only supported where dart:io is available.
  var uri = Uri.parse(uploadUrl);
  var request = http.MultipartRequest('POST', uri)
    ..fields['file_name'] = "${username!}_$fileName"
    ..fields['username'] = username
    ..files.add(await http.MultipartFile.fromPath('file', filePath));

  http.Response response =
      await http.Response.fromStream(await request.send());
  // debugPrint("Result: ${response.body}");

  //解决json解析中的乱码问题
  Utf8Decoder utf8decoder = const Utf8Decoder(); // fix 中文乱码
  //将string类型数据 转换为json类型的数据
  final responseJson = json.decode(utf8decoder.convert(response.bodyBytes));
  debugPrint("upload image responseJson $responseJson");
  //
  return UploadJsonResult.fromJson(responseJson);
}