Flutter 单张图片选择上传功能以及多张图片选择

import 'package:dio/dio.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:image_picker/image_picker.dart';
                  InkWell(
                    onTap: () => _getImageFromGallery(),
                    child: Text("54555555555555555"),
                  )
  Future _getImageFromGallery() async {
    var image = await ImagePicker().pickImage(source: ImageSource.gallery);
    File file = File(image!.path);//需要把XFile转换成File
    Uploadimage(file);
  }

    Uploadimage(File file) async {
// 单个文件上传,格式一定要注意
    var formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(file.path, filename: 'upload.txt'),
      "userId": 22,
    });

// 多个文件上传
// FormData.fromMap({
//   'files': [
//     MultipartFile.fromFileSync('./example/upload.txt', filename: 'upload.txt'),
//     MultipartFile.fromFileSync('./example/upload.txt', filename: 'upload.txt'),
//   ]
// });

    try {
      Response response;
      Dio dio = new Dio();
      response = await dio.post(
        url,
        data: formData,
        options: Options(contentType: "multipart/form-data"),
      );
      print(response);
    } catch (e) {
      return print(e);
    }
  }


多张图片选择参考链接:
插件:https://pub.flutter-io.cn/packages/multi_image_picker/example
文章:https://blog.csdn.net/sky_asd/article/details/104245149

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

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

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

class _MyAppState extends State {
  List images = [];
  String _error = 'No Error Dectected';
  FormData formData4 = FormData();


  @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 loadAssets() async {
    List resultList = [];
    String error = 'No Error Detected';

    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;
    });
    
    for (int i = 0; i < images.length; i++) {
      // 获取 ByteData
      ByteData byteData = await images[i].getByteData();
      List imageData = byteData.buffer.asUint8List();

      MultipartFile multipartFile = MultipartFile.fromBytes(
        imageData,
        // 文件名
        filename: 'some-file-name.png',
        // 文件类型
        contentType: MediaType("image", "png"),
      );

      setState(() {
        formData = FormData.fromMap({
          "file": multipartFile,
          "userId": id,
        });
      });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Center(child: Text('Error: $_error')),
            ElevatedButton(
              child: Text("Pick images"),
              onPressed: loadAssets,
            ),
            Expanded(
              child: buildGridView(),
            )
          ],
        ),
      ),
    );
  }
}

你可能感兴趣的:(flutter,flutter,前端)