Flutter 调用原生硬件 Api 实现照相机 拍照和相册选择 以及拍照上传
Posted zhaofeis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter 调用原生硬件 Api 实现照相机 拍照和相册选择 以及拍照上传相关的知识,希望对你有一定的参考价值。
一、Flutter image_picker 实现相机拍照和相册选择
https://pub.dev/packages/image_picker
二、Flutter 上传图片到服务器
https://pub.dev/packages/dio
上传2.0 dio: 2.1.7
//上传图片
_uploadImage(_imageDir) async{
FormData formData = new FormData.from({
"name": "zhangsna 6666666666",
"age": 20,
"sex":"男",
"file":new UploadFileInfo(_imageDir, "xxx.jpg"),
});
var response = await Dio().post("http://jd.itying.com/imgupload", data: formData);
print(response);
}
案例代码 上传3.0
import ‘dart:io‘;
import ‘package:flutter/material.dart‘;
import ‘package:image_picker/image_picker.dart‘;
import ‘package:dio/dio.dart‘;
class CameraPage extends StatefulWidget{
CameraPage({Key key});
_CameraPage createState() => _CameraPage();
}
class _CameraPage extends State {
var cameraImg;
var albumImg;
// 相机
getCameraImg() async {
var camera = await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 100);
uploadImg(camera);
setState(() {
cameraImg = camera;
});
}
// 相册
getAlbumImg() async {
var album = await ImagePicker.pickImage(source: ImageSource.gallery, maxWidth: 100);
setState(() {
albumImg = album;
});
}
// 上传图片
uploadImg(File imgUrl) async {
var path = imgUrl.path;
var formData = FormData.fromMap({
"name": "wendux",
"age": 25,
"file": MultipartFile.fromFileSync(path, filename: "upload.img")
});
var response = await Dio().post("https://pub.dev/packages/dio", data: formData);
print(response);
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text(‘设备硬件‘)
),
body: ListView(
children: <Widget>[
RaisedButton(child: Text(‘相机 上传图片‘), onPressed: () {
getCameraImg();
}),
cameraImg == null ? SizedBox(height: 0) : Container(
height: 100,
child: Image.file(cameraImg),
),
RaisedButton(child: Text(‘相册‘), onPressed: getAlbumImg),
albumImg == null ? SizedBox(height: 0) : Container(
height: 100,
child: Image.file(albumImg),
)
],
)
);
}
}
以上是关于Flutter 调用原生硬件 Api 实现照相机 拍照和相册选择 以及拍照上传的主要内容,如果未能解决你的问题,请参考以下文章