Bootstrap

Flutter Web 选取并上传图片

选取图片

  /// 选取图片
  void pickImage() async {
    final input = html.FileUploadInputElement();
    // 单选
    input.multiple = false;
    input.accept = 'image/*';

    // 显示文件选择对话框
    html.document.body?.append(input);
    input.click();

    await input.onChange.first;

    // 获取选中的文件列表
    final files = input.files;
    if (files?.first.name.isEmpty == true) {
      return;
    }
    final file = files!.first;
    if (!await beforeUpload(file)) {
      input.remove();
      return;
    }

    final reader = html.FileReader();
    reader.onLoadEnd.listen((e) {
      final result = reader.result as Uint8List;
      uploadImage(result, file);
    });
    reader.readAsArrayBuffer(file);
  }

校验图片合法性

  /// 对上传的文件进行校验
  Future<bool> beforeUpload(html.File file) async {
    final size = await file.size;
    bool isSize = size / 1024 / 1024 < 15;
    if (!isSize) {
      print("超过15M限制,不允许上传~");
      return false;
    }
    // 添加对文件后缀名的限制
    final suffix =
        file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
    final isSuffixByJpgOrPng =
        (suffix == 'jpg' || suffix == 'jpeg' || suffix == 'png');
    final isJpgOrPng = file.type == 'image/jpg' ||
        file.type == 'image/jpeg' ||
        file.type == 'image/png';

    if (!isSuffixByJpgOrPng || !isJpgOrPng) {
      print("只能上传JPG、JPEG、PNG格式的图片~'");
      return false;
    }
    return true;
  }

使用http上传图片

  /// 上传文件
  void uploadImage(Uint8List data, html.File file) async {
    try {
      var request = http.MultipartRequest(
          'POST', Uri.parse('https://cdn.server.com/api/upload'));
      request.files.add(http.MultipartFile.fromBytes('file', data,
          filename: file.name, contentType: MediaType.parse(file.type)));

      final response = await request.send();
      if (response.statusCode == 200) {
        final jsonStr = await response.stream.bytesToString();
        final jsonData = jsonDecode(jsonStr);
        /// TODO 处理请求成功之后的数据
      }
    } catch (e) {
      print("upload error -> $e");
    }
  }
;