ESP32 通过 POST 发送图片内容

要通过 ESP32 发送图片,需要将图片转换为字节数组,并使用 HTTP POST 请求将其发送到服务器。以下是一个示例代码,其中使用了 ESP32 内置的 HTTP 客户端库:

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

const char* ssid = 'your_SSID';
const char* password = 'your_PASSWORD';
const char* url = 'http://your_server_url/upload.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('/test.jpg', 'r');
  if (!file) {
    Serial.println('Failed to open file');
    return;
  }

  // 将图片转换为字节数组
  uint8_t* image = (uint8_t*) malloc(file.size());
  file.read(image, file.size());
  file.close();

  // 发送 POST 请求
  HTTPClient http;
  http.begin(url);
  http.addHeader('Content-Type', 'application/octet-stream');
  http.addHeader('Content-Length', String(file.size()));
  int httpResponseCode = http.POST(image, file.size());
  if (httpResponseCode > 0) {
    // 成功上传图片
    Serial.printf('HTTP Response code: %d\n', httpResponseCode);
  } else {
    Serial.printf('HTTP Error code: %d\n', httpResponseCode);
  }
  http.end();

  free(image);
}

void loop() {
  // 程序循环
}

在此示例中,我们首先连接到 WiFi 网络,然后使用 SPIFFS 库读取名为 'test.jpg' 的图像文件。我们将图像转换为字节数组,并使用 HTTPClient 库的 begin() 方法初始化 POST 请求。我们还添加了 Content-Type 和 Content-Length 标头,以指示服务器我们正在发送的是二进制数据。最后,我们使用 POST() 方法发送图像数据,并检查服务器的响应代码以确定是否成功上传了图像。

ESP32 发送图片到服务器:使用 HTTP POST 方法

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

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