flutter 上传图片 image_picker 的使用

Github地址: https://github.com/flutter/plugins/tree/master/packages/image_picker

packages地址: https://pub.dev/packages/image_picker

 

1、将其添加到包的pubspec.yaml文件中:

image_picker: ^0.4.5

 

2、安装

flutter pub get

 

3、导入

import 'package:image_picker/image_picker.dart';

 

4、上传图片的两种方式

使用相机

var image = await ImagePicker.pickImage(source: ImageSource.camera);

使用图库

var image = await ImagePicker.pickImage(source: ImageSource.gallery);

 

5、上传图片

  _openGallery() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    ShopPaperImgDao.uploadImg(image).then((res){
      if(res['code'] == 200){
        // 上传成功
      }else{}
    }).catchError((e){
      print(e.toString());
    });
  }

  ShopPaperImgDao.uploadImg 的方法  

import 'dart:async';
import 'dart:io';
import 'package:dio/dio.dart';

class ShopPaperImgDao {
  // 上传图片
  static Future uploadImg(imgfile) async{
    String path = imgfile.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData = new FormData.from({
      "file": new UploadFileInfo(new File(path), name)
    });
    Response response;
    Dio dio =new Dio();
    response =await dio.post('后端接口',data: formData);
    if(response.statusCode == 200){
      return response.data;
    }else{
      throw Exception('后端接口异常');
    }
  }
}

 

6、结语

代码里面的 path,name,formData 可自行 print 查看。这里就不一一讲述了。 image_picker 自行查看 dart package 最新版本。    

注意:

flutter pub get 之后可能需要重新 flutter run

 

    原文作者:_whys
    原文地址: https://www.cnblogs.com/wyhlightstar/p/11082675.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞