前言 Flutter 文件/图片 上传
使用 Flutter框架 基于 http.dart 网络库 ImagePicker.pickImage 进行的 App开发:
今天开发过程中 需要上传 图片:看了下官方文档竟然没有介绍的!!!
后来 google 搜索到了在这里记录下:
这三种方式的选型 需要和你后台上传方式对应上,否则就没办法上传成功!自然就是报 500,我这里选择的是三种
Flutter 基于http 库 上传文件的几种方式:
- http.MultipartFile
(String filename, String url) async { var request = http.MultipartRequest('POST', Uri.parse(url)); request.files.add( http.MultipartFile( 'picture', File(filename).readAsBytes().asStream(), File(filename).lengthSync(), filename: filename.split("/").last ) ); var res = await request.send(); }
- http.MultipartFile.fromBytes
(String filename, String url) async { var request = http.MultipartRequest('POST', Uri.parse(url)); request.files.add( http.MultipartFile.fromBytes( 'picture', File(filename).readAsBytesSync(), filename: filename.split("/").last ) ); var res = await request.send(); }
- http.MultipartFile.fromPath
(String filename, String url) async { var request = http.MultipartRequest('POST', Uri.parse(url)); request.files.add( await http.MultipartFile.fromPath( 'picture', filename ) ); var res = await request.send(); }
代码:
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
Future<ResponseBase> upLoadFiles(
{required String pathCode, required String filePath}) async {
try {
AppOverlay().showLoading();
Uri url = Uri.https(AppHost.hostFile, 'Images/ImageSingleUpload');
http.MultipartRequest request = http.MultipartRequest('POST', url);
request.fields['pathCode'] = pathCode;
http.MultipartFile multipartFile =
await http.MultipartFile.fromPath("image", filePath);
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
//这里返回值用到了Stream回调
String res = await response.stream.bytesToString();
Map<String, dynamic> jsonResponse =
convert.jsonDecode(res) as Map<String, dynamic>;
ResponseBase _responseBase = ResponseBase(
errorCode: jsonResponse['errorCode'],
action: jsonResponse['action'],
message: jsonResponse['message'],
value: jsonResponse['value'],
success: jsonResponse['success'],
);
return _responseBase;
} else {
return ResponseBase(
errorCode: response.statusCode,
action: 0,
message: '上传文件失败 请稍后再试 ${response.statusCode}',
success: false,
value: {'error get'},
);
}
} catch (exception) {
AppScreen.showToast('上传文件失败 请稍后再试 ${exception.toString()}');
return ResponseBase(
errorCode: -100,
action: 0,
message: '网络异常 请稍后再试 -100',
success: false,
value: {'error get': exception.toString()},
);
} finally {
AppOverlay().hideLoading();
}
}
今天的文章Flutter 文件上传 (基于 http.dart)分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/30339.html