PS: 圖片上傳功能在項(xiàng)目中屬于很常見的功能,網(wǎng)上也有蠻多圖片上傳的框架张吉,看的眼花繚亂的辅斟。。芦拿。最后士飒,本著自己最熟悉的才是最好的原則選擇 Flutter Dio,所以項(xiàng)目中用的網(wǎng)絡(luò)框架也是Flutter Dio ,直接拿來(lái)寫個(gè)簡(jiǎn)單的demo蔗崎,也算記錄下Flutter踩坑心酸史吧酵幕。。缓苛。
- 國(guó)際慣例(為了省事沒做圖片大小限制了芳撒。。未桥。)
廢話不多說(shuō)了笔刹,直接上代碼,
- 先添加兩個(gè)依賴:
dio: any
flutter_picker: ^1.0.11
不熟悉dio的小伙伴可以去看看 Dio
- 全部應(yīng)用代碼直接貼出來(lái)(dio可自行封裝冬耿,這里只演示極簡(jiǎn)版)
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
class HeadImageUploadPage extends StatefulWidget {
@override
_HeadImageUploadPageState createState() => _HeadImageUploadPageState();
}
class _HeadImageUploadPageState extends State<HeadImageUploadPage> {
File _image;
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
_upLoadImage(image);
setState(() {
_image = image;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker Example'),
),
body: Center(
child: _image == null
? Text('No image selected.')
: Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
_upLoadImage(File image) async {
String path = image.path;
var name = path.substring(path.lastIndexOf("/") + 1, path.length);
var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
FormData formData = new FormData.from({
"userId": "10000024",
"file": new UploadFileInfo(new File(path), name,
contentType: ContentType.parse("image/$suffix"))
});
Dio dio = new Dio();
var respone = await dio.post<String>("/upload", data: formData);
if (respone.statusCode == 200) {
Fluttertoast.showToast(
msg: "圖片上傳成功",
gravity: ToastGravity.CENTER,
textColor: Colors.grey);
}
}
}