PS: 图片上传功能在项目中属于很常见的功能,网上也有蛮多图片上传的框架,看的眼花缭乱的。。。最后,本着自己最熟悉的才是最好的原则选择 Flutter Dio,所以项目中用的网络框架也是Flutter Dio ,直接拿来写个简单的demo,也算记录下Flutter踩坑心酸史吧。。。
- 国际惯例(为了省事没做图片大小限制了。。。)
废话不多说了,直接上代码,
- 先添加两个依赖:
dio: any
flutter_picker: ^1.0.11
不熟悉dio的小伙伴可以去看看 Dio
- 全部应用代码直接贴出来(dio可自行封装,这里只演示极简版)
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);
}
}
}