Flutter Web相机图片获取异常:Blob链接无法读取问题求助
Flutter Web相机拍照Blob URL转可上传文件解决方案
在Flutter Web环境下,camera插件拍照返回的Blob URL无法通过dart:io的File读取,需要借助浏览器原生API将Blob转换为可上传的二进制数据,以下是具体解决方案:
修改拍照后的处理逻辑
替换原有拍照代码,改用浏览器API读取Blob内容并转换为Uint8List,再封装为MultipartFile发送至Flask后端:
import 'dart:html' as html; import 'package:http/http.dart' as http; import 'package:http_parser/http_parser.dart'; // 按钮点击事件中的拍照处理 await _initializeControllerFuture; final image = await _controller.takePicture(); // 1. 从Blob URL获取Blob对象 final blobResponse = await html.HttpRequest.request( image.path, responseType: 'blob', ); final blob = blobResponse.response as html.Blob; // 2. 将Blob转换为Uint8List final reader = html.FileReader(); reader.readAsArrayBuffer(blob); await reader.onLoad.first; final uint8List = reader.result as Uint8List; // 3. 封装为MultipartFile,准备上传 final multipartFile = http.MultipartFile.fromBytes( 'image', // 对应Flask后端接收的字段名 uint8List, filename: 'camera_photo.png', contentType: MediaType('image', 'png'), ); // 4. 发送POST请求到Flask后端 final request = http.MultipartRequest( 'POST', Uri.parse('http://localhost:5000/face-detect'), // 替换为你的Flask接口地址 ); request.files.add(multipartFile); final response = await request.send(); // 处理响应 if (response.statusCode == 200) { print('上传成功'); } else { print('上传失败,状态码:${response.statusCode}'); }
关键注意事项
- 避免使用dart:io的File:Web环境下
dart:io.File不支持Blob URL,必须依赖dart:html的API处理浏览器Blob对象 - Flask后端接收处理:后端需要解析
multipart/form-data格式的请求,示例代码:from flask import Flask, request from flask_cors import CORS app = Flask(__name__) CORS(app) # 配置跨域支持 @app.route('/face-detect', methods=['POST']) def face_detect(): image_file = request.files.get('image') # 此处执行人脸检测逻辑 return {'status': 'success'} - 跨域配置:必须给Flask后端添加跨域支持,否则浏览器会拦截上传请求
内容的提问来源于stack exchange,提问作者ronel
相关产品推荐
相关产品推荐

