【问题标题】:how to upload multiple images using multi_image_picker: ^4.6.7 and Dio in flutter?如何使用 multi_image_picker: ^4.6.7 和 Dio 上传多张图片?
【发布时间】:2020-08-05 17:56:23
【问题描述】:

我是 Flutter 新手,在使用 multi_image_pickerdio 将图像上传到服务器时遇到问题。

我已经使用multi_image_picker成功获取了多张图片,但未能将图片上传到服务器。

请帮忙。

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:multi_image_picker/multi_image_picker.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Asset> images = List<Asset>();
  String _error = 'No Error Dectected';

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

  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,
        );
      }),
    );
  }

  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: "Example App",
          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;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: <Widget>[
            Center(child: Text('Error: $_error')),
            RaisedButton(
              child: Text("Pick images"),
              onPressed: loadAssets,
            ),
            Expanded(
              child: buildGridView(),
            )
          ],
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.file_upload),
          onPressed: () {
            print(images);
          },
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    使用multi_image_picker 类。如何在flutter/dart中使用restAPI上传图片文件

    // string to uri
    Uri uri = Uri.parse('enter api url here');
    
    // create multipart request
    MultipartRequest request = http.MultipartRequest("POST", uri);
    
    ByteData byteData = await asset.getByteData();
    List<int> imageData = byteData.buffer.asUint8List();
    
    MultipartFile multipartFile = MultipartFile.fromBytes(
     'photo',  //key of the api
     imageData,
     filename: 'some-file-name.jpg',
     contentType: MediaType("image", "jpg"), //this is not nessessory variable. if this getting error, erase the line.
    );
    
    // add file to multipart
    request.files.add(multipartFile);
    // send
    var response = await request.send();
    

    命名空间

    import 'dart:convert';
    import 'dart:async';
    import 'package:http/http.dart' as http;
    import 'package:http/http.dart';
    

    【讨论】:

      【解决方案2】:

      只需要创建每个图像的Multipart对象。

      可以从 Assets 中获取字节数组

       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);
                }
      

      FYI

      【讨论】:

        猜你喜欢
        • 2020-05-03
        • 2020-08-11
        • 2020-12-27
        • 2019-10-14
        • 2020-12-27
        • 2023-03-23
        • 2019-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多