配置 image_picker 插件。
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
date_format: ^1.0.6
flutter_cupertino_date_picker: ^1.0.26+2
flutter_swiper: ^1.1.6
fluttertoast: ^7.1.6
http: ^0.12.2
flutter_html: ^1.1.0
flutter_inappwebview: ^4.0.0+4
device_info: ^1.0.0
amap_location: ^0.2.0
# 上传图片
dio: ^3.0.10
# 拍照上传
image_picker: ^0.6.7+21
在pubspec.yaml中配置保存后,在VS Code环境中会自动下载依赖包。
如果无法正常下载,执行 flutter pub get 。
在需要用到的该插件的文件中引入插件包。
import 'package:image_picker/image_picker.dart';
// 图片文件
File _image;
// 实例化
final picker = ImagePicker();
// 获取图片方法
Future getImage() async {
final pickedFile = await picker.getImage(
// 拍照获取图片
// source: ImageSource.camera,
// 手机选择图库
source: ImageSource.gallery,
// 图片的最大宽度
maxWidth: 400
);
// 更新状态
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
} else {
print('没有选择任何图片');
}
});
}
引入插件包。
import 'package:dio/dio.dart';
编写上传的方法。
var dio = Dio();
// 上传图片的方法
void uploadImg(imageUrl) async{
FormData formData = FormData.fromMap({
"name": "admin",
"password": 123456,
"file": await MultipartFile.fromFile(
imageUrl,
filename: "avatar.img"
)
});
var result = await dio.post("http://js.itying.com/imgupload", data: formData);
print(result);
}
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class ImagePickerPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _ImagePickerState();
}
}
class _ImagePickerState extends State<ImagePickerPage> {
// 图片文件
File _image;
// 实例化
final picker = ImagePicker();
// 获取图片
Future getImage() async {
final pickedFile = await picker.getImage(
// 拍照获取图片
// source: ImageSource.camera,
// 手机选择图库
source: ImageSource.gallery,
// 图片的最大宽度
maxWidth: 400
);
// 更新状态
setState(() {
if (pickedFile != null) {
_image = File(pickedFile.path);
// 上传图片到服务器
uploadImg(pickedFile.path);
} else {
print('没有选择任何图片');
}
});
}
var dio = Dio();
// 上传图片的方法
void uploadImg(imageUrl) async{
FormData formData = FormData.fromMap({
"name": "admin",
"password": 123456,
"file": await MultipartFile.fromFile(
imageUrl,
filename: "avatar.img"
)
});
var result = await dio.post("http://js.itying.com/imgupload", data: formData);
print(result);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("ImagePicker"),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// 点击按钮
RaisedButton(
onPressed: getImage,
child: Text("获取图片"),
),
// 展示图片
Center(
child: _image == null
? Text('没有选择任何图片')
: Image.file(_image),
),
],
)
)
);
}
}
参考: