You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中HTTP请求响应体为空问题排查(Facebook广告图上传场景)

How to Properly Retrieve Response Body When Uploading Images to Facebook Ads API in Dart

I’ve faced this exact problem when working with the Facebook Ads API in Dart, so let’s break down what’s causing the empty response and how to fix it.

The Root Cause

Your original code uses a regular Map for the request body, which the http package encodes as application/x-www-form-urlencoded. However, the -F flag in curl tells it to send the request as multipart/form-data—the correct format for uploading files. Facebook’s API expects this multipart format, so even though it returns a 200 status code, it’s not processing the file upload correctly, hence the empty response body.

Solution 1: Using the http Package Correctly

Instead of http.post() with a regular map, you need to use MultipartRequest to build a proper multipart form data request. Here’s the corrected code:

import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

// ... your existing variables (path, ACCESS_TOKEN, AD_ACCOUNT_ID)

Future<void> uploadImage() async {
  final request = http.MultipartRequest(
    'POST',
    Uri.parse('https://graph.facebook.com/v8.0/act_$AD_ACCOUNT_ID/adimages'),
  );

  // Add the access token as a form field
  request.fields['access_token'] = ACCESS_TOKEN;

  // Add the image file to the request
  // Adjust the contentType to match your image type (e.g., image/png for PNGs)
  request.files.add(await http.MultipartFile.fromPath(
    'filename',
    path,
    contentType: MediaType('image', 'jpeg'),
  ));

  // Send the request and convert the streamed response to a regular Response
  final streamedResponse = await request.send();
  final response = await http.Response.fromStream(streamedResponse);

  if (response.statusCode == HttpStatus.ok) {
    print("Upload successful!");
    print(response.body); // This should now return the expected API response
  } else {
    throw Exception('Failed to upload image: ${response.body}');
  }
}

Solution 2: Using the Dio Package Correctly

If you prefer using Dio, you need to build a FormData object with a proper MultipartFile instead of a plain string for the file. Here’s how to fix that:

import 'package:dio/dio.dart';

// ... your existing variables

Future<void> uploadImageWithDio() async {
  final formData = FormData.fromMap({
    'access_token': ACCESS_TOKEN,
    'filename': await MultipartFile.fromFile(
      path,
      contentType: MediaType('image', 'jpeg'), // Match your image type
    ),
  });

  final response = await Dio().post(
    'https://graph.facebook.com/v8.0/act_$AD_ACCOUNT_ID/adimages',
    data: formData,
  );

  if (response.statusCode == HttpStatus.ok) {
    print("Upload successful!");
    print(response.data); // You'll get the correct response data here
  } else {
    throw Exception('Failed to upload image: ${response.data}');
  }
}

Key Notes

  • Always specify the correct contentType for your image (e.g., image/png for PNG files, image/gif for GIFs) to ensure Facebook’s API processes the file correctly.
  • Using MultipartRequest (for http) or FormData with MultipartFile (for Dio) ensures the request is sent in the multipart/form-data format that curl uses, which is required for file uploads to the Facebook Ads API.

内容的提问来源于stack exchange,提问作者Ramses Kouam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:57:39