从颤动发送 base64 图像

我最近遇到了一个奇怪的问题。我必须将一个 base64 编码的图像从 flutter 发送到远程 API。问题是我使用以下代码转换图像:

Future getProfileImage() async {
    final _pickedFile =
        await _imagePicker.getImage(source: ImageSource.gallery);
    _profileImage = await File(_pickedFile!.path);
    print("${_pickedFile.toString()}");
    //print("${_pickedFile.path}");
    List<int> _profileImageBytes = await _profileImage!.readAsBytesSync();
    _profileImageBase64 = await base64Encode(_profileImageBytes);

    print("$_profileImageBase64");
  }

但是当我尝试使用以下代码发送时:

Future updateProfile() async {
    print("$_profileImageBase64");
    String pre = "data:image/jpg;base64,";
    String imageString = '';
    print("$imageString");
    if (_profileImageBase64 == null) {
      imageString = '';
    } else {
      imageString = "$pre$_profileImageBase64";
    }
    String apiUrl = "http://162.0.236.163:3000/api/users/profile-update";
    Map<String,String> header = {
      'Content-Type': 'application/x-www-form-urlencoded','Authorization': "Bearer ${widget.user.token}"
    };
    print(
        "Bearer ${widget.user.token},${_firstName!.controller!.text},${_lastName!.controller!.text}");
    //print("$imageString");
    //log(imageString);
    Map<String,String> body = {
      'firstName': _firstName!.controller!.text,'lastName': _lastName!.controller!.text,'image': imageString
    };
    print("${body["image"]}");
    http.Response reponse =
        await http.post(Uri.parse(apiUrl),body: body,headers: header);
    //print("${jsonDecode(reponse.body)}");
    var data = jsonDecode(reponse.body) as Map;
    print("$data");
    if (data["status"] == 1) {
      widget.user.first = _firstName!.controller!.text;
      widget.user.last = _lastName!.controller!.text;
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('firstName',widget.user.first.toString());
      prefs.setString('lastName',widget.user.last.toString());
    }
    setState(() {});
  }

失败了。奇怪的是,当我在上述方法的开头打印字符串时,它显示不同的值,但是当我打印 body["image"] 时,它是略有不同的字符串。此外,令人惊讶的是,当我从控制台复制这些字符串中的任何一个,并将它们硬编码为图像字符串时,代码成功了。我无法弄清楚为什么我无法使用 String 变量成功发送图像,该变量实际上具有相同的代码。请问有人可以帮忙吗?

编辑:我刚刚意识到该字符串可能无法完全打印在控制台中。当我检查字符串的长度时,base64(220kb 文件)几乎有 314000 个字符。但是在控制台中出现了数千个。控制台中的一个可以成功 已发送,但完整字符串失败。会不会是服务器端的限制

nghnyh 回答:从颤动发送 base64 图像

好吧,如果授权没有问题,并且成功保存了较短的字符串,那么听起来像是在限制该字段或整个字段的服务器端 (API) 上执行了某种形式的数据验证消息正文。

如果数据存储在数据库中,请确保图像字段足够大以容纳那么多字符。

尝试的一个建议是在将图像转换为 base64 之前减小图像的大小。 'image_picker' 包中的 getImage 方法有一些可选参数,允许您指定 maxHeight(宽度将成比例)和图像质量。

import 'dart:async';
import 'dart:io' as Io;
import 'dart:convert';
import 'package:image_picker/image_picker.dart';

final pickedFile = await picker.getImage(
  source: ImageSource.gallery,maxHeight: 150,imageQuality: 90,);

final bytes = await pickedFile.readAsBytes();
final b64img = base64.encode(bytes);
本文链接:https://www.f2er.com/830.html

大家都在问