Flutter调用remove.bg API上传图片遇卡顿及类型转换错误
解决remove.bg API图片去背景的请求问题
问题详情
- 使用普通HTTP POST请求调用remove.bg API时,抛出错误:
Error in removeBg: type 'MultipartFile' is not a subtype of type 'String' in type cast - 使用
MultipartRequest发送请求时应用卡顿,日志仅打印到请求发送阶段,更换dio库后问题依旧
错误原因分析
- 普通POST请求报错:
http.post的body参数仅支持字符串类型的键值对,不能直接传入MultipartFile对象,文件上传必须使用专门的MultipartRequest构造请求。 - 请求卡顿:原代码中
image!.readAsBytes().asStream()会先将整个图片文件读取到内存,若图片体积较大,会阻塞主线程引发卡顿;同时原代码未完整处理响应流,导致请求看似“卡住”。
修正后的代码实现
1. 使用http库的正确实现
Future<void> removeBg() async { final uri = Uri.parse("https://api.remove.bg/v1.0/removebg"); final headers = {'X-API-Key': "t1689LyUTModrnaHgKRjsJuk"}; try { final request = http.MultipartRequest("POST", uri) ..headers.addAll(headers) // 用fromPath直接获取文件流,避免一次性加载整个文件到内存 ..files.add(await http.MultipartFile.fromPath( "image_file", image!.path, filename: image!.path.split("/").last, )); final response = await request.send(); // 完整读取响应流,获取返回数据 final responseBytes = await response.stream.toBytes(); if (response.statusCode == 200) { setState(() { _isLoaded = true; responseImage = responseBytes; }); } else { final errorMsg = utf8.decode(responseBytes); print("API请求失败,状态码: ${response.statusCode},错误信息: $errorMsg"); } } catch (e) { print("removeBg出错: $e"); } }
2. 使用dio库的正确实现
import 'package:dio/dio.dart'; Future<void> removeBgWithDio() async { final dio = Dio(); final uri = "https://api.remove.bg/v1.0/removebg"; final headers = {'X-API-Key': "t1689LyUTModrnaHgKRjsJuk"}; try { final formData = FormData.fromMap({ "image_file": await MultipartFile.fromFile( image!.path, filename: image!.path.split("/").last, ), }); final response = await dio.post( uri, options: Options(headers: headers), data: formData, responseType: ResponseType.bytes, // 直接获取图片二进制数据 ); if (response.statusCode == 200) { setState(() { _isLoaded = true; responseImage = response.data; }); } else { print("API请求失败,状态码: ${response.statusCode}"); } } catch (e) { print("removeBgWithDio出错: $e"); } }
关键优化点
- 使用官方提供的
fromPath/fromFile方法处理文件上传,高效读取文件流,避免内存过载。 - 完整读取响应流,确保请求流程闭环,消除“卡顿”假象。
- 错误时解析响应内容,便于排查API返回的具体问题。
内容的提问来源于stack exchange,提问作者Jeevan Shrestha
相关产品推荐
相关产品推荐

