簡體   English   中英

同時發送圖片和文字 flutter

[英]send image and text at the same time flutter

我想同時使用 HTTP 發布方法上傳圖像和其他類型的數據,如字符串和 integer。 但我收到錯誤代碼說 json 無法編碼圖像文件,我在 flutter 上有此代碼:

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 發布請求上發送圖像和文本,而無需使用多部分請求分離圖像?

您可以在請求 header 中獲取您的資產數據:

  var response = await client.post(
    uri,
    headers: {
      "Content-type": "application/json",
      "Authorization": "Bearer ${User.token}",
      "asset-data": jsonEncode(
        <String, dynamic>{
          "name": asset.name,
          "condition": asset.condition,
          "purchase_date": asset.purchaseDate,
          "price": asset.price,
          "location": asset.location,
          "description": asset.description
        },
      ),
    },
    body: imageFile.readAsBytesSync(),
  );

這將需要您修改服務器端代碼以從 header 中讀取。

要在 POST 的請求正文中包含圖像,通常您必須將其轉換為多部分文件,然后將其作為 formdata 包含在正文中。 這要求服務器在從客戶端接收圖像時期望表單數據本身中的多部分文件。

我想為您推薦這款 package 名稱dio 它支持 MultipartFile、FormData 和其他強大的輔助類。

這是一個例子:

static Future<bool> sendImage(String imagePath) async {
    try {
      final content = MultipartFile.fromFile(imagePath);
      final contentType = 'multipart/form-data';
      final Response response = await dio.post('$BASE_URL/$images',
          data: FormData.fromMap({'file': content}),
          options: Options(contentType: contentType));
      if (response.statusCode == 200) {
        return true;
      }
      return false;
    } catch (error) {
      return null;
    }
  }

您可以在此處閱讀有關FormData的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM