1

我正在使用multi_image_pickerAssets从图库中进行选择,这工作正常。如何选择File使用相同库的图像?

这是我从multi_image_picker文档中获得的代码,

import 'package:exa/Controller/DatabaseHelper.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'dart:async';


class UpdateStatus extends StatefulWidget {
  @override
  _UpdateStatusState createState() => _UpdateStatusState();
}

class _UpdateStatusState extends State<UpdateStatus> {

  DatabaseHelper databaseHelper=new DatabaseHelper();

  List<Asset> images = List<Asset>();
  String error = 'Error Dectected';



  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Create Post'),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.all(18.0),
            child: InkWell(
              child: Text(
                'POST',
                style: TextStyle(fontSize: 18.0),
              ),
              onTap: () async {

                  print('work');
                /*
                for (int i = 0; i < images.length; i++) {
                  var path = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
                  print(path);
                }
                */
                  databaseHelper.uploadpostsimages(images);


              },
            ),
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[


              Container(
                height: 200.0,
                color: Colors.white,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: TextFormField(
                    keyboardType: TextInputType.multiline,
                    maxLines: 100,
                    style: new TextStyle(fontSize: 18.0, color: Colors.black),
                    decoration: InputDecoration(
                      hintText: 'Enter your Post Details Here !',
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),

              Divider(
                thickness: 1.0,
              ),
              Column(
                children: <Widget>[
                  Container(
                    height: 40.0,
                    color: Colors.white70,
                    child: Padding(
                      padding: EdgeInsets.only(
                        left: 18.0,
                      ),
                      child: InkWell(
                        child: Row(
                          children: <Widget>[
                            Icon(
                              Icons.add_a_photo,
                            ),
                            Text(
                              "  Choose Image",
                              style: TextStyle(
                                fontSize: 24.0,
                              ),
                            ),
                          ],
                        ),
                        onTap: loadAssets,
                      ),
                    ),
                  ),
                  Divider(
                    thickness: 1.0,
                  ),
                  Container(
                    height: 40.0,
                    color: Colors.white70,
                    child: Padding(
                      padding: EdgeInsets.only(
                        left: 18.0,
                      ),
                      child: InkWell(
                        child: Row(
                          children: <Widget>[
                            Icon(
                              Icons.add_photo_alternate,
                            ),
                            Text(
                              "  Choose Video",
                              style: TextStyle(
                                fontSize: 24.0,
                              ),
                            ),
                          ],
                        ),
                        onTap: () {
                          print('choose video from local');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              Divider(
                thickness: 1.0,
              ),
              Container(
                height: 200,
                child: Column(
                  children: <Widget>[
                    Expanded(
                      child: buildGridView(),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 300,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        materialOptions: MaterialOptions(
          actionBarColor: "#abcdef",
          actionBarTitle: "Ilma",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      images = resultList;
      error = error;
    });
  }

  Widget buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];

        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }


}
4

1 回答 1

1

我认为您不需要图像作为文件。您可以从 multi_image_picker 获取资产列表,它可以使用AssetThumb()方法显示。

AssetThumb(
  asset: asset,
  width: 100,
  height: 100,),

并将其上传到服务器,您可以从资产中获取字节数组

ByteData byteData = await asset.getByteData();
  List<int> imageData = byteData.buffer.asUint8List();

然后它可以通过MultipartFile.fromBytes()方法。

所以它看起来像,

 String url = "upload/url";

          List<Asset> images = List<Asset>();
          List<MultipartFile> multipartImageList = new List<MultipartFile>();
          if (null != images) {
            for (Asset asset in images) {
              ByteData byteData = await asset.getByteData();
              List<int> imageData = byteData.buffer.asUint8List();
              MultipartFile multipartFile = new MultipartFile.fromBytes(
                imageData,
                filename: 'load_image',
                contentType: MediaType("image", "jpg"),
              );
              multipartImageList.add(multipartFile);
            }

            FormData formData = FormData.fromMap({
              "multipartFiles": multipartImageList,
              "userId": '1'
            });

            Dio dio = new Dio();
            var response = await dio.post(url, data: formData);
          }
于 2020-09-30T07:03:32.753 回答