Flutter上传、显示二进制图像的一些事

一. 二进制流图像的显示

前端图像的展示,我们最常用的是给定一个图像地址,然后它就会自己加载并显示,如这样的代码:


这基本是一种数据的Get请求,对于像Post之类的请求方式,上述方式就不好用了,这个时候可以列用数据流或二进制方式处理,在Flutter可以像下面文章处理:

flutter通过dio读取二进制数据,比如通过api接口读取图片

但是此文的方法已经过期了,我调整了一下(里面有额外获取Headers的代码,可去掉)

  ///
  /// 获取图片
  static Future getImage(String url) async {
    Dio dio = Dio();
    // 注意:这里使用bytes
    dio.options.responseType = ResponseType.bytes;
    // 如果headers有东西,则添加
    Map headers = Map();
    dio.options.headers = headers;
    try {
      Response response = await dio.post(url);
      String codeId = '';
      // 获取response的headers信息,如果业务不需要可以去掉
      final List imageCode = response.headers["code-id"];
      if (imageCode != null && imageCode.length > 0) {
        codeId = imageCode[0];
      }
      final Uint8List bytes = consolidateHttpClientResponseBytes(response.data);
      print("获取图像成功");
      print(codeId);
      return ImageCodeModel(codeId, bytes);
    } catch (e) {
      print("网络错误:" + e.toString());
      return await null;
    }
  }

  static consolidateHttpClientResponseBytes(data) {
    // response.contentLength is not trustworthy when GZIP is involved
    // or other cases where an intermediate transformer has been applied
    // to the stream.
    final List> chunks = >[];
    int contentLength = 0;
    chunks.add(data);
    contentLength += data.length;
    final Uint8List bytes = Uint8List(contentLength);
    int offset = 0;
    for (List chunk in chunks) {
      bytes.setRange(offset, offset + chunk.length, chunk);
      offset += chunk.length;
    }
    return bytes;
  }

二. 图像的上传

对于图像的上传,网上一些文章是这样写的:

  void upload(String url, File file) {
    print(file.path);
    Dio dio = Dio();
    dio.post(url, data: FormData.from({'file': file}))
    ...

这种方式其实对于新版的Flutter和Dio也已经不适用了,而是应如下方式调用

  static const TIME_OUT = 60000;
  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  ///
  ///上传文件
  static Future uploadFile(String url, File file) async {
    String path = file.path;
    var fileData = await MultipartFile.fromFile(
      path
    );
    FormData formData = FormData.fromMap({
      "file": fileData,
    });
    Options options = new Options(method: "POST");
    ///超时
    options.receiveTimeout = TIME_OUT;
    Map headers = new HashMap();
    headers[Config.tokenName] = SPService.getToken();
    headers[HttpHeaders.contentTypeHeader] = CONTENT_TYPE_FORM;
    headers[HttpHeaders.acceptHeader] = CONTENT_TYPE_JSON;
    options.headers = headers;
    return request(url, formData, options: options);
  }

你可能感兴趣的:(Flutter上传、显示二进制图像的一些事)