如何将Python requests图片上传代码转换为Flutter HTTP或Dio实现
Flutter 端Google图搜上传接口的代码转换
两种主流网络包的实现逻辑,均和你提供的Python代码、curl命令的请求行为完全对齐:所有必填的multipart表单字段不会遗漏,默认自动跟随重定向,生成的请求格式和原实现完全一致。
基于官方http包的实现
需要先在项目依赖中引入http包,核心代码如下:
import 'dart:io'; import 'package:http/http.dart' as http; Future<http.Response> uploadImageToGoogleSearch(String localImagePath) async { // 初始化POST类型的multipart请求 final request = http.MultipartRequest( 'POST', Uri.parse('https://www.google.co.in/searchbyimage/upload'), ); // 完全对齐Python代码中的表单字段值 request.fields.addAll({ 'image_url': '', 'image_content': '', 'filename': '', 'h1': 'en', 'bih': '179', 'biw': '1600', }); // 加载本地图片,映射到encoded_image表单字段 request.files.add( await http.MultipartFile.fromPath('encoded_image', localImagePath), ); // 发送请求,自动跟随重定向,返回最终响应 final streamedResponse = await request.send(); return await http.Response.fromStream(streamedResponse); }
注意:
http包的MultipartRequest默认开启重定向跟随,和原Python代码allow_redirects=True的行为完全一致。
基于dio包的实现
dio是Flutter生态中更常用的网络请求库,语法更简洁,核心实现如下:
import 'dart:io'; import 'package:dio/dio.dart'; Future<Response> uploadImageWithDio(String localImagePath) async { final dio = Dio(); // 构造和原逻辑一致的multipart表单数据 final formData = FormData.fromMap({ // 对齐Python代码的固定字段值 'image_url': '', 'image_content': '', 'filename': '', 'h1': 'en', 'bih': '179', 'biw': '1600', // 加载本地图片文件映射到encoded_image字段 'encoded_image': await MultipartFile.fromFile( localImagePath, filename: 'image.jpg', ), }); // 发送请求,默认自动跟随重定向 final response = await dio.post( 'https://www.google.co.in/searchbyimage/upload', data: formData, ); return response; }
常见踩坑说明
- 不要省略原Python代码中值为空的三个字段(
image_url/image_content/filename),如果只上传图片和几个尺寸参数,Google的接口会直接返回400错误 - 不需要手动设置multipart请求的
Content-Type头,两个网络包在构造文件上传请求时会自动生成符合规范的边界值,和curl-F命令生成的请求格式完全一致 - 两个包的默认重定向策略均为开启状态,和原Python代码的配置无差异,不需要额外编写重定向处理逻辑
内容的提问来源于stack exchange,提问作者Yash Makan
相关产品推荐
相关产品推荐

