【发布时间】:2021-03-17 00:21:13
【问题描述】:
我想同时使用 HTTP post 方法上传图像和其他类型的数据,如字符串和整数。但我得到错误代码说 json 无法编码图像文件,我在颤振上有这个代码:
static Future<ApiReturnValue<Asset>> addAsset(Asset asset, File imageFile,
{http.Client client}) async {
client ??= http.Client();
String url = baseUrl + 'asset';
var uri = Uri.parse(url);
var response = await client.post(
uri,
headers: {
"Content-type": "application/json",
"Authorization": "Bearer ${User.token}"
},
body: jsonEncode(
<String, dynamic>{
"name": asset.name,
"condition": asset.condition,
"purchase_date": asset.purchaseDate,
"price": asset.price,
"location": asset.location,
"description": asset.description,
"image": imageFile,
},
),
);
if (response.statusCode != 200) {
return ApiReturnValue(message: "Add item failed, please try again");
}
var data = jsonDecode(response.body);
Asset value = Asset.fromJson(data['data']['asset']);
return ApiReturnValue(value: value);
}
有什么方法可以同时在 HTTP 发布请求上发送图像和文本,而无需使用多部分请求分离图像?
【问题讨论】:
-
嗨,有趣的是,也许对图像进行 base64 编码,以便它可以嵌入到 json 中?不会像单独发送它那样有效。
-
好的,我试试,谢谢
标签: flutter