Flutter Web向Python Flask API传图报错:Unsupported operation: _Namespace
Flutter Web 上传图片到 Flask API 解决「Unsupported operation: _Namespace」错误
问题核心是Flutter Web 中无法直接使用 dart:io 的 File 对象——移动端的 File 依赖本地文件系统操作,而 Web 环境没有对应的权限与实现,调用 file.lengthSync()、file.readAsBytes() 这类方法会直接抛出异常。
解决步骤
区分平台处理文件源
- 移动端继续使用
image_picker等插件获取dart:io.File - Web 端使用
dart:html的FileUploadInputElement选择文件,获取dart:html.File对象
- 移动端继续使用
重构上传逻辑,适配 Web 环境
不能复用移动端的MultipartFile创建逻辑,Web 端需要基于dart:html.File构建请求体。
修改后的代码示例
先导入对应包(注意平台条件导入):
import 'dart:async'; import 'package:http/http.dart' as http; // 仅 Web 环境导入 dart:html import 'dart:html' as html; // 移动端导入 dart:io // import 'dart:io';
跨平台上传函数实现:
Future<http.Response> getRecommendation(dynamic file, String link) async { String filename; Stream<List<int>> fileStream; int fileLength; // 区分 Web 和移动端文件处理逻辑 if (file is html.File) { filename = file.name; fileStream = file.openRead(); fileLength = file.size; } else if (file is File) { // 移动端的 dart:io.File filename = file.path.split('/').last; fileStream = file.readAsBytes().asStream(); fileLength = file.lengthSync(); } else { throw Exception("不支持的文件类型"); } var request = http.MultipartRequest( 'POST', Uri.parse(link), ); // 无需手动设置 Content-type: multipart/form-data,http 包会自动生成带 boundary 的正确头 request.files.add( http.MultipartFile( 'image', fileStream, fileLength, filename: filename, ), ); var res = await request.send(); var response = await http.Response.fromStream(res); return response; }
Web 端文件选择示例
Future<html.File?> pickFileWeb() async { final input = html.FileUploadInputElement() ..accept = 'image/*'; input.click(); await input.onChange.first; if (input.files?.isEmpty ?? true) return null; return input.files!.first; }
内容的提问来源于stack exchange,提问作者KEZIA ANGELINE
相关产品推荐
相关产品推荐

