flutter从图库获取本地图片,然后上传到服务器
进入图库选择参考
上传图片参考
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'data/ModifyBaseInfo.dart';
class ImagePickerWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _ImagePickerState();
class _ImagePickerState extends State<ImagePickerWidget> {
var _imgPath;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF222222),
appBar: AppBar(
leading: Container(
margin: const EdgeInsets.only(left: 10.0),
width: 20,
title: const Text("修改头像"),
backgroundColor: const Color(0xFF222222),
centerTitle: true,
actions: [
GestureDetector(
onTap: () {
modifyAvatar();
child: Center(
child: Container(
margin: const EdgeInsets.only(right: 15.0),
child: const Text("保存"),
)),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
_ImageView(_imgPath),
GestureDetector(
onTap: () {
_takePhoto();
child: Container(
padding: const EdgeInsets.only(
top: 10, bottom: 10, left: 20, right: 20),
decoration: BoxDecoration(color: Colors.blue),
child: const Text(
"拍照",
style: TextStyle(color: Colors.white),
GestureDetector(
onTap: () {
_openGallery();
child: Container(
margin: const EdgeInsets.only(top: 10),
padding: const EdgeInsets.only(
top: 10, bottom: 10, left: 20, right: 20),
decoration: BoxDecoration(color: Colors.blue),
child: const Text(
"选择图片",
style: TextStyle(color: Colors.white),
));
modifyAvatar() async {
var apiUrl = "http://47.242.63.216:9527/v1/user/setAvatar";
String path = _imgPath.toString();
String path1 = path.substring(7);
String path2 = path1.substring(0, path1.length - 1);
SharedPreferences prefs = await SharedPreferences.getInstance();
String? tokens = prefs.getString("token");
Map<String, dynamic> map = Map();
map["head"] = await MultipartFile.fromFile(path2, filename: "23.png");
FormData formData = FormData.fromMap(map);
Response result = await Dio().post(apiUrl,
data: formData, options: Options(headers: {"x-token": tokens}));
debugPrint("${result}");
Map<String, dynamic> nickname = json.decode(result.toString());
var httpRes = ModifyBaseInfo.fromJson(nickname);
if (httpRes.code == 200) {
Fluttertoast.showToast(
msg: "${httpRes.msg}",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 10,
backgroundColor: Colors.white,
textColor: Colors.black,
fontSize: 16.0);
Navigator.pop(context);
Widget _ImageView(imgPath) {
if (imgPath == null) {
return const Center(
child: Text(
"请选择图片或拍照",
style: TextStyle(color: Colors.white),
} else {
return Image.file(
imgPath,
Future _takePhoto() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
setState(() {
_imgPath = image;
print("$_imgPath");
});
_openGallery() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_imgPath = image;
});
上传到服务器后再通过接口获取图片就是网络地址了,就可以通过显示网络图片的方式去显示图片了
Container(
width: 50,
height: 50,
margin: EdgeInsets.only(right: 10.0),
decoration: BoxDecoration(
image: DecorationImage(
image:
NetworkImage(mAvatar),
fit: BoxFit.cover,
borderRadius: BorderRadius.circular(50),
flutter从图库获取本地图片,然后上传到服务器进入图库选择参考上传图片参考import 'dart:convert';import 'package:dio/dio.dart';import 'package:flutter/material.dart';import 'package:fluttertoast/fluttertoast.dart';import 'package:image_picker/image_picker.dart';import 'package:shared
文章目录导入依赖包multi_image_picker的使用显示图片上传图片可能遇到的问题
在Android中从手机相册选择一些图片出来是很常用的功能。Flutter也提供了很好用的第三方库可以帮助我们快速实现这个需求。
实现效果如下
接下来看看该怎么用。
导入依赖包
版本号可以到puv.dev上查找最新的替换上去。
dependencies:
multi_image_picker: ^4.6.1
multi_image_picker的使用
使用这个插件也很简单。首先导入包
import 'pack
为了完全自定义照片上传字段,需要几个回调和类。 在大多数情况下,您将混合来自远程源和本地上载的照片。 对于这些,适配器层很有用:
class ImageInputAdapter {
/// Initialize from either a URL or a file, but not both.
ImageInputAdapter ({
this .file,
this .url
}) : assert (file != null || url != null ), assert (file != null && url == null ), assert (file == null && url != null );
/// An image file
final Fil
Map<String, dynamic> map = Map();
map["video"] = await MultipartFile.fromFile(video, filename: "23.mp4");
map["photos"] = await MultipartFile.fromFile(thumbPath);
FormData formData = FormData.fromMap(map);
//网络请求添加token请求头
Respo
1.只是一个dome,供借鉴使用,待优化
2. 这个手写画板借鉴了很多的github上面的内容,基本就是用github上的内容拼凑出来的,随后我会把github上相关的链接写上去
3. 全部代码(注意依赖的包)
// An highlighted block
import 'dart:io';
import 'dart:async';
import 'dart:ui' as ui;
import ...
Flutter 是一个跨平台的移动应用框架,可以用来开发 Android 和 iOS 等应用。如果你想使用 Flutter 上传文件,你可以使用 `http` 包里的 `MultipartRequest` 来实现。
首先,你需要导入 `http` 包:
import 'package:http/http.dart' as http;
然后,你可以使用以下代码来创建一个 `MultipartRequest` 对象并上传文件:
// 创建请求
var request = http.MultipartRequest('POST', Uri.parse('http://example.com/upload'));
// 添加文件
request.files.add(await http.MultipartFile.fromPath('file', 'path/to/your/file.ext'));
// 发送请求
var response = await request.send();
// 处理响应
response.stream.transform(utf8.decoder).listen((value) {
print(value);
注意:你需要自己处理文件上传过程中可能出现的各种错误,例如网络错误、文件路径不存在等。