ESP32 使用 HTTP POST 发送图片:完整代码示例

本教程将向您展示如何使用 ESP32 通过 HTTP POST 方法将图片发送到远程服务器。

代码示例

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverName = "http://your_server_name.com/upload_image.php"; // 服务器接收图片的 URL

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // 读取图片数据
  File file = SPIFFS.open("/image.jpg", "r");
  if (!file) {
    Serial.println("Failed to open file for reading");
    return;
  }
  uint8_t* imageBuffer = (uint8_t*)malloc(file.size());
  file.read(imageBuffer, file.size());
  file.close();

  // 创建 HTTPClient 对象
  HTTPClient http;

  // 设置 POST 请求头
  http.begin(serverName);
  http.addHeader("Content-Type", "image/jpeg");

  // 发送 POST 请求
  int httpResponseCode = http.POST(imageBuffer, file.size());

  // 处理响应
  if (httpResponseCode > 0) {
    String response = http.getString();
    Serial.println(httpResponseCode);
    Serial.println(response);
  } else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }

  // 释放内存
  free(imageBuffer);
  http.end();
}

void loop() {
  // do nothing
}

代码解释

  1. 包含必要的库:
  • WiFi.h: 用于连接 WiFi 网络。
  • HTTPClient.h: 用于创建 HTTP 客户端对象。
  1. 定义变量:
  • ssid: 您的 WiFi 网络名称。
  • password: 您的 WiFi 密码。
  • serverName: 服务器接收图片的 URL。
  1. 连接 WiFi:
  • 使用 WiFi.begin() 连接到您的 WiFi 网络。
  1. 读取图片数据:
  • 使用 SPIFFS.open() 打开名为 "image.jpg" 的图片文件。
  • 使用 malloc() 分配内存来存储图片数据。
  • 使用 file.read() 读取图片数据到内存中。
  • 使用 file.close() 关闭文件。
  1. 创建 HTTPClient 对象:
  • 使用 HTTPClient() 创建一个 HTTP 客户端对象。
  1. 设置 POST 请求头:
  • 使用 http.begin() 设置请求的 URL。
  • 使用 http.addHeader() 设置 Content-Type 头为 "image/jpeg",表示要发送的图片类型。
  1. 发送 POST 请求:
  • 使用 http.POST() 发送图片数据到服务器。
  1. 处理响应:
  • 检查 httpResponseCode 的值。如果大于 0,则表示请求成功。
  • 使用 http.getString() 获取服务器返回的响应。
  1. 释放内存:
  • 使用 free() 释放之前分配的内存。
  • 使用 http.end() 关闭 HTTP 客户端对象。

注意事项

  • 确保您的服务器已设置好接收图片数据并处理上传请求。
  • 此代码示例仅适用于 JPEG 格式的图片。如果您要发送其他格式的图片,请相应地更改 Content-Type 头。
  • 如果您的图片文件大小超过 ESP32 的可用内存,则需要使用 SD 卡或其他存储设备来存储图片数据。
ESP32 使用 HTTP POST 发送图片:完整代码示例

原文地址: https://www.cveoy.top/t/topic/jOco 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录