【flutter上传图片】

1.使用multi_image_picker插件

dart 复制代码
//选择图片
openPhotoSelect(int maxImages,context) async {
    try {
      List<Asset> images = await MultiImagePicker.pickImages(
        maxImages: maxImages - state.selectImageList.length,
        enableCamera: true,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarTitle: "图片选择",
          allViewTitle: "所有图片",
          useDetailsView: true,
          selectCircleStrokeColor: "#4dc8b6",
          selectionLimitReachedText: "最多选择$maxImages张图片",
        ),
      );

      state.selectImageList.addAll(file);
      state.publishType = 1;
      update();
    } on Exception catch (e) {
      print(e);
    }
  }

//上传图片
  Future<bool> uploadImagesData() async {
    state.imageVideoParamList.clear();
    ByteData byteData;
    List<int> imageData;
    MultipartFile multipartFile;
    FormData formData;
    Response response;
    Dio dio = Dio();

    if(state.selectImageList.length > 0){
      for (int i = 0; i < state.selectImageList.length; i++) {
        Asset asset = state.selectImageList[i];
        byteData = await asset.getByteData();
        imageData = byteData.buffer.asUint8List();
        multipartFile =
            MultipartFile.fromBytes(imageData, filename: "${asset.name}");
        formData = FormData.fromMap({
          "android": "1",
          "file": multipartFile,
        });
        
        multipartFile =
            MultipartFile.fromBytes(file.path, filename: "${asset.name}");
        formData = FormData.fromMap({
          "android": "1",
          "file": multipartFile,
        });

        response = await dio.post('${MyApi.UPLOAD_FILE}', data: formData);
        if (response.statusCode == 200 && response.data['code'] == 200) {
          state.uploadIndex = i + 1;
          if (i == 0) {
            state.image = response.data['data'] /*+
                '?Size=${asset.originalWidth}x${asset.originalHeight}'*/;

            state.imageVideoParamList.add(
                {
                  'type':'P',
                  'url':'${response.data['data'] +
                      '?Size=${asset.originalWidth}x${asset.originalHeight}'}'
                }
            );

            update();
          } else {
            state.image = "${state.image};" +
                response.data['data'] +
                '?Size=${asset.originalWidth}x${asset.originalHeight}';
            state.imageVideoParamList.add(
                {
                  'type':'P',
                  'url':'${response.data['data'] +
                      '?Size=${asset.originalWidth}x${asset.originalHeight}'}'
                });
            update();
          }
        }
      }
      // 图片上传结束
      if (state.selectImageList.length > state.uploadIndex) {
        // 部分图片上传失败
        state.uploadIndex = null;
        return false;
      }
    }
    return true;
  }

2.使用wechat_assets_picker插件

dart 复制代码
// 打开图片选择
  openPhotoSelect(int maxImages,context) async {
    try {
      List<AssetEntity> images = await AssetPicker.pickAssets(
          context,
          maxAssets: maxImages - state.selectImageList.length
      );
      images.forEach((element) async {
        File file = await element.file;
        state.selectImageList.add(file);
      });
      state.publishType = 1;
      update();
    } on Exception catch (e) {
      print(e);
    }
  }

//上传图片
  Future<bool> uploadImagesData() async {
    state.imageVideoParamList.clear();
    ByteData byteData;
    List<int> imageData;
    MultipartFile multipartFile;
    FormData formData;
    Response response;
    Dio dio = Dio();

    if(state.selectImageList.length > 0){
      for (int i = 0; i < state.selectImageList.length; i++) {
        File file = state.selectImageList[i];
        String imageName = file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
        multipartFile =
            MultipartFile.fromFileSync(file.path, filename: "$imageName");
        formData = FormData.fromMap({
          "android": "1",
          "file": multipartFile,
        });

        response = await dio.post('${MyApi.UPLOAD_FILE}', data: formData);
        if (response.statusCode == 200 && response.data['code'] == 200) {
          state.uploadIndex = i + 1;
          if (i == 0) {
            state.image = response.data['data'];

            state.imageVideoParamList.add(
                {
                  'type':'P',
                  'url':'${response.data['data']}'
                }
            );

            update();
          } else {
            state.image = "${state.image};" +
                response.data['data'];

            state.imageVideoParamList.add(
                {
                  'type':'P',
                  'url':'${response.data['data']}'
                });
            update();
          }
        }
      }
      // 图片上传结束
      if (state.selectImageList.length > state.uploadIndex) {
        // 部分图片上传失败
        state.uploadIndex = null;
        return false;
      }
    }

    return true;
  }

选择视频

dart 复制代码
/// 视频选择
  void openVideoSelect(BuildContext context) async {
    PickedFile pickedFile =
    await ImagePicker().getVideo(source: ImageSource.gallery);
    File videoFile = File(pickedFile.path);
    //state.videoPath = videoFile.path;
    update();
    VideoPlayerController _controller = VideoPlayerController.file(videoFile);
    _controller.initialize().then((_) async {
      Duration duration = _controller.value.duration;
      if (duration.inSeconds > 60) {
        esLoadingToast('发布视频长度不能大于1分钟');
      } else {
        // 解码视频
        Loading.showLoading(context);
       bool end = await openVideoEncode(videoFile.path);
       if(end){
         Loading.hideLoading(context);
       }
      }
    });
  }
相关推荐
你听得到112 小时前
从需求到封装:手把手带你打造一个高复用、可定制的Flutter日期选择器
前端·flutter
哲科软件12 小时前
跨平台开发的抉择:Flutter vs 原生安卓(Kotlin)的优劣对比与选型建议
android·flutter·kotlin
天涯海风12 小时前
Kuikly 与 Flutter 的全面对比分析,结合技术架构、性能、开发体验等核心维度
flutter·kuikly
aiprtem12 小时前
基于Flutter的web登录设计
前端·flutter
coder_pig16 小时前
跟🤡杰哥一起学Flutter (三十四、玩转Flutter手势✋)
前端·flutter·harmonyos
程序员老刘18 小时前
Android 16开发者全解读
android·flutter·客户端
Jalor19 小时前
Flutter + 鸿蒙 | Flutter 跳转鸿蒙原生界面
flutter·harmonyos
吴Wu涛涛涛涛涛Tao21 小时前
一步到位:用 Very Good CLI × Bloc × go_router 打好 Flutter 工程地基
flutter·ios
九丝城主21 小时前
2025使用VM虚拟机安装配置Macos苹果系统下Flutter开发环境保姆级教程--中篇
服务器·flutter·macos·vmware
ITfeib1 天前
Flutter
开发语言·javascript·flutter