如何使用multi_image_picker:^ 4.6.7和Dio抖动来上传多张图片?

时间:2020-08-05 17:56:23

标签: flutter dart

我是新手,我在使用multi_image_picker和dio将图像上传到服务器时遇到了问题。 我是新手,在使用multi_image_picker和dio将图像上传到服务器时遇到了问题。

我已经成功地使用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);
          },
        ),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:2)

使用 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';

答案 1 :(得分:1)

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

您可以从资产中获取字节数组

 this.dataService.deleteMeaningItem({id: id}).subscribe(res => {
 if (res.status) {
    //do something          
  }
  });

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

所以看起来像

deleteMeaningItem(data): Observable<Result> {
     return this.http.delete<Result>(global.dataUrl + '/MeaningItems/Delete', { params: data,
     headers: {'Content-Type': 'application/json'}});
}

FYI