Flutter 实现拍照上传功能
- 组件库:image_picker.dart,dio.dart
- 在学习过程中遇到这样一个问题,网上给出的很多案例中再给file赋值时使用的是
"UploadFileInfo"这个方法。如:"file": await UploadFileInfo.fromFile(path, filename: name),由于flutter更新以后不在支持"UploadFileInfo",所以需要把 "UploadFileInfo" 替换成 "MultipartFile"
-
使用的都是FormData formData = FormData.fromMap({ //文件信息 "file": await MultipartFile.fromFile(path, filename: name), //传参信息 "faultSysNo": '66666' });
-
import 'dart:io'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:image_picker/image_picker.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: PhotoDemo(), ); } } class PhotoDemo extends StatefulWidget { final dynamic data; PhotoDemo({this.data}); @override _PhotoDemoState createState() => _PhotoDemoState(); } class _PhotoDemoState extends State<PhotoDemo> { ScrollController _scrollController = ScrollController(); @override void initState() { // TODO: implement initState super.initState(); } //记录选择的照片 File _image; //拍照 Future _getImageFromCamera() async { //获取文件信息 var image = // ignore: deprecated_member_use await ImagePicker.pickImage(source: ImageSource.camera, maxWidth: 400); setState(() { _image = image; }); } Dio _dio; //上传文件 void _upLoadImage() async { String path = _image.path; var name = path.substring(path.lastIndexOf("/") + 1, path.length); // FormData formData = FormData.fromMap({ //文件信息 "file": await MultipartFile.fromFile(path, filename: name), //传参信息 "faultSysNo": '66666' }); //post请求上传文件 var data = await _dio.post("/API/UploadFault", data: formData); if (data != null) {} } @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; // 命名宽度 final _width = size.width; // 屏幕高度 final _height = size.height; return Scaffold( appBar: AppBar( title: Text('照相机'), ), body: Container( alignment: Alignment.center, child: Row(children: <Widget>[ Expanded( child: Container( alignment: FractionalOffset.centerLeft, margin: EdgeInsets.only(top: 10), child: Text("拍照上传:", style: TextStyle(fontSize: 17.0, color: Colors.black)), ), ), Expanded( child: Container( alignment: FractionalOffset.center, margin: EdgeInsets.only(left: 10, top: 10), child: RaisedButton( child: Icon( Icons.add_a_photo, color: Colors.grey, ), color: Colors.white, onPressed: () { _getImageFromCamera(); }, )), ) ]), )); } }