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

posted @ 2019-11-20 10:40  生如逆旅,一苇以航  阅读(2372)  评论(0编辑  收藏  举报