首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Flutter中将多张图片上传到API?

如何在Flutter中将多张图片上传到API?
EN

Stack Overflow用户
提问于 2021-07-26 09:08:10
回答 2查看 64关注 0票数 0

在我的应用程序中,用户应该能够在服务器上上传多个图像(一次超过8个图像)?我可以一次上传一张图片,但我不能一次上传多张图片?请建议我怎么做,这对我会有帮助吗?谢谢。下面是我的代码:

代码语言:javascript
运行
AI代码解释
复制
final List<File> _image = [];
final picker = ImagePicker();

final pickedFile = await picker.pickImage(source: ImageSource.camera,imageQuality: 100);
                   if(pickedFile != null){
                     File? croppedFile = await ImageCropper.cropImage(sourcePath: pickedFile.path,
                     aspectRatioPresets: [
                       CropAspectRatioPreset.square,
                       CropAspectRatioPreset.ratio3x2,
                       CropAspectRatioPreset.original,
                       CropAspectRatioPreset.ratio4x3,
                       CropAspectRatioPreset.ratio16x9
                     ],
                       androidUiSettings: const AndroidUiSettings(
                         toolbarTitle: 'Cropper',
                         toolbarColor: Colors.blueGrey,
                         toolbarWidgetColor: Colors.white,
                         activeControlsWidgetColor: Colors.blueGrey,
                         initAspectRatio: CropAspectRatioPreset.original,
                         lockAspectRatio: false,
                       ),
                         iosUiSettings: const IOSUiSettings(
                           minimumAspectRatio: 1.0,
                         )
                     );
                     if(croppedFile != null){
                       setState(() {
                         // _scanQrCode = croppedFile.path;
                         imageFile = croppedFile.path;
                         imageFile = _scanQrCode;
                         print(imageFile);
                         _image.add(File(croppedFile.path));
                       });
                     }
                   }
EN

回答 2

Stack Overflow用户

发布于 2021-07-26 09:16:09

您可以尝试使用flutter_uploader

导入包:

代码语言:javascript
运行
AI代码解释
复制
import 'package:flutter_uploader/flutter_uploader.dart';

Initialize uploader:这是一个单例对象

代码语言:javascript
运行
AI代码解释
复制
final uploader = FlutterUploader();

创建新的上传任务:

代码语言:javascript
运行
AI代码解释
复制
final taskId = await uploader.enqueue(
  url: "your upload link", //required: url to upload to
  files: [FileItem(filename: filename, savedDir: savedDir, fieldname:"file")], // required: list of files that you want to upload
  method: UploadMethod.POST, // HTTP method  (POST or PUT or PATCH)
  headers: {"apikey": "api_123456", "userkey": "userkey_123456"},
  data: {"name": "john"}, // any data you want to send in upload request
  showNotification: false, // send local notification (android only) for upload status
  tag: "upload 1"); // unique tag for upload task
);

监听上传进度

代码语言:javascript
运行
AI代码解释
复制
  final subscription = uploader.progress.listen((progress) {
      //... code to handle progress
  });

监听上传结果

代码语言:javascript
运行
AI代码解释
复制
  final subscription = uploader.result.listen((result) {
      //... code to handle result
  }, onError: (ex, stacktrace) {
      // ... code to handle error
  });

注意:当任务被取消时,它将在onError处理程序上作为状态=已取消的异常发送

取消上传任务:

代码语言:javascript
运行
AI代码解释
复制
uploader.cancel(taskId: taskId);

取消所有上传任务:

代码语言:javascript
运行
AI代码解释
复制
uploader.cancelAll();
票数 0
EN

Stack Overflow用户

发布于 2021-09-12 22:11:14

您可以使用Dio包进行单个/多个/动态数量的图片上传。

套餐

代码语言:javascript
运行
AI代码解释
复制
dio: ^4.0.0
image_picker: ^0.8.3+3

导入包

代码语言:javascript
运行
AI代码解释
复制
import 'package:dio/dio.dart' as Dio;
import 'package:image_picker/image_picker.dart';

对于已知数量的图像(例如:2个图像)

代码语言:javascript
运行
AI代码解释
复制
XFile? pickedFile1;
XFile? pickedFile2;

void selectImage1(ImageSource imageSource) async {
    try {
      pickedFile1 = await ImagePicker().pickImage(source: imageSource);
    } finally {
    }
  }

 void selectImage2(ImageSource imageSource) async {
    try {
      pickedFile2 = await ImagePicker().pickImage(source: imageSource);
    } finally {
    }
  }

  void create() async {
    try {
        if (pickedFile1 != null) {
          Dio.FormData formData = new Dio.FormData.fromMap({
            "name": name.text,
            "year": year.text,
            "image_1": await Dio.MultipartFile.fromFile(pickedFile1!.path,
                filename: pickedFile1!.path.split('/').last),
            "image_2": await Dio.MultipartFile.fromFile(pickedFile2!.path,
                filename: pickedFile2!.path.split('/').last)
          });
          await VehicleServices.create(formData);
        } else {}
    } catch (e) {} finally {
    }
  }

VehicleServices类

代码语言:javascript
运行
AI代码解释
复制
static Future<bool> create(FormData data) async {
    try {
      Response response =
      await Dio().post(
        "$baseURL/vehicles",
        data: data,
      );
      if(response.statusCode==201){
        return true;
      }
      return false;
    } catch(e){
      return false;
    }
  }

图像的动态数量(例如: 0,1,2,3)

代码语言:javascript
运行
AI代码解释
复制
List<XFile> pickedFile = [];

void selectImage() async {
    try {
      pickedFile = (await ImagePicker().pickMultiImage())!;
    } finally {
    }
 }

  void create() async {
    try {
        var arr = [];
        for (var img in pickedFile) {
          arr.add(await Dio.MultipartFile.fromFile(img.path,
              filename: img.path.split('/').last));
        }
        Dio.FormData formData = new Dio.FormData.fromMap({
          "name": name.text,
          "images": arr
        });
        await GalleryServices.create(formData);
    } catch (e) {} finally {
    }
  }

GalleryServices类

代码语言:javascript
运行
AI代码解释
复制
 static Future<bool> create(FormData data) async {
    try {
      Response response =
      await Dio().post(
        "$baseURL/galleries",
        data: data,
      );
      if(response.statusCode==201){
        return true;
      }
      return false;
    } catch(e){
      return false;
    }
  }

带源代码的演示- https://youtu.be/Zhd4uBEkXBk

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68527192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档