flutter 文件上传封装

发布时间:2024年01月02日
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:atui/jade/utils/Utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import '../../http/api/my_api.dart';
import 'dart:ui' as ui;

class UploadImageRequest {
//MyApi.UPLOAD_FILE上传文件的接口

  ///多图上传图片获取url
  static Future<List<String>> uploadManyImagesData(
      List<Asset> selectImageList) async {
    ByteData byteData;
    List<int> imageData;
    MultipartFile multipartFile;
    FormData formData;
    Response response;
    Dio dio = Dio();
    List<String> imageUrlList = [];
    for (int i = 0; i < selectImageList.length; i++) {
      Asset asset = selectImageList[i];
      byteData = await asset.getByteData();
      imageData = byteData.buffer.asUint8List();
      multipartFile =
          MultipartFile.fromBytes(imageData, 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) {
        String image = response.data['data'] +
            '?Size=${asset.originalWidth}x${asset.originalHeight}';
        imageUrlList.add(image);
        print(image);
      }
    }
    return Future.value(imageUrlList);
  }

  //通过File文件路径加载Image对象
  static Future<ui.Image> loadImageFromFile(String uri) async {
    ImageStream stream = new FileImage(
      File.fromUri(Uri.parse(uri)),
    ).resolve(ImageConfiguration.empty);
    Completer<ui.Image> completer = new Completer<ui.Image>();
    ImageStreamListener listener;
    listener = new ImageStreamListener((ImageInfo frame, bool synchronousCall) {
      final ui.Image image = frame.image;
      completer.complete(image);
      stream.removeListener(listener);
    });
    stream.addListener(listener);
    return completer.future;
  }

  ///单图上传图片获取url
  static Future<String> uploadSingleImagesData(String filePath) async {
    Response response;
    String image;
    Dio dio = Dio();
    FormData imageFormData;
    var name =
        filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length);

    imageFormData = FormData.fromMap({
      "file": await MultipartFile.fromFile(
        filePath,
        filename: name,
      ),
      "android": "1",
    });
    dio.options.connectTimeout = 600000;
    response = await dio.post('${MyApi.UPLOAD_FILE}', data: imageFormData);
    if (response.statusCode == 200 && response.data['code'] == 200) {
      ui.Image img = await loadImageFromFile(filePath);
      image = response.data['data'] + '?Size=${img.width}x${img.height}';
      print(image);
    }
    return Future.value(image);
  }

  ///上传视频
  static Future<String> uploadVideo(String videoPath) async {
    var name;
    MultipartFile multipartFile;
    FormData formData;
    Response response;
    String videoUrl;
    Logger().w(videoPath);

    /// 获取视频名称
    name =
        videoPath.substring(videoPath.lastIndexOf("/") + 1, videoPath.length);
    multipartFile = MultipartFile.fromFileSync(videoPath, filename: name);
    formData = FormData.fromMap({
      "android": "1",
      "file": multipartFile,
    });
    Dio dio = Dio();
    response = await dio.post('${MyApi.UPLOAD_FILE}', data: formData,
        onSendProgress: (count, data) {
      /// 监听上传进度
    });
    if (response.statusCode == 200 && response.data['code'] == 200) {
      print(response.data['data']);
      videoUrl = response.data['data'];
    } else {
      return Future.error(null);
    }
    return Future.value(videoUrl);
  }


  //多图上传(File类型)
  static Future<List<String>> uploadImages(List<File> imageList) async {
    MultipartFile multipartFile;
    FormData formData;
    Response response;
    Dio dio = Dio();
    int uploadIndex;
    List<String> imageUrlList = [];

    for (int i = 0; i < imageList.length; i++) {
      File file = imageList[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) {
        uploadIndex = i + 1;
        imageUrlList.add(response.data['data']);
      }
    }
    // 图片上传结束
    if (imageList.length > uploadIndex) {
      // 部分图片上传失败
      uploadIndex = null;
      print('部分图片上传失败,从第${uploadIndex + 1}张失败');
      //如果有部分图片上传失败则清空已经上传返还的图片链接(图片上传失败)
      imageUrlList.clear();
    }
    return Future.value(imageUrlList);
  }

  //多图上传(通过文件路径)
  static Future<List<String>> uploadImagesByPath(List<String> images) async {
    String imageName;
    MultipartFile multipartFile;
    FormData formData;
    Response response;
    int originalWidth,originalHeight;
    List<String> imageUrlList = [];
    int uploadIndex;
    Dio dio = Dio();
    for (int i = 0; i < images.length; i++) {
      originalWidth =  await Utils().getLocalImageWidth(images[i]);
      originalHeight = await Utils().getLocalImageHeight(images[i]);
      imageName = images[i].substring(images[i].lastIndexOf("/") + 1, images[i].length);
      multipartFile =
          MultipartFile.fromFileSync(images[i], 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) {
        uploadIndex = i + 1;
        imageUrlList.add('${response.data['data'] + '?Size=${originalWidth}x${originalHeight}'}');
      }
    }
    // 图片上传结束
    if (images.length > uploadIndex) {
      // 部分图片上传失败
      uploadIndex = null;
      print('部分图片上传失败,从第${uploadIndex + 1}张失败');
      //如果有部分图片上传失败则清空已经上传返还的图片链接(图片上传失败)
      imageUrlList.clear();
    }
    return Future.value(imageUrlList);
  }

}
调用,例如:List<String> imageUrlList = await UploadImageRequest.uploadImages(state.selectImageList);
文章来源:https://blog.csdn.net/androidhyf/article/details/135343578
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。