ESP32-CAM 上传图片到服务器:使用 multipart/form-data POST 请求
您可以使用以下代码将图像作为'multipart/form-data' POST请求上传到服务器:
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <esp_camera.h>
#include "esp_http_client.h"
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverUrl = "http://your_server_url/upload.php";
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");
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = 5;
config.pin_d1 = 18;
config.pin_d2 = 19;
config.pin_d3 = 21;
config.pin_d4 = 36;
config.pin_d5 = 39;
config.pin_d6 = 34;
config.pin_d7 = 35;
config.pin_xclk = 0;
config.pin_pclk = 22;
config.pin_vsync = 25;
config.pin_href = 23;
config.pin_sscb_sda = 26;
config.pin_sscb_scl = 27;
config.pin_pwdn = 32;
config.pin_reset = -1;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
config.frame_size = FRAMESIZE_SXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
}
void loop() {
// Take a photo
camera_fb_t* fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
return;
}
// Prepare the HTTP request
WiFiClient client;
HTTPClient http;
http.begin(client, serverUrl);
http.addHeader("Content-Type", "multipart/form-data");
// Prepare the image data as a multipart form data
esp_http_client_config_t config = {
.url = serverUrl,
.method = HTTP_METHOD_POST,
.event_handler = NULL,
};
esp_http_client_handle_t client2 = esp_http_client_init(&config);
esp_http_client_set_header(client2, "Content-Type", "multipart/form-data");
esp_http_client_set_post_field(client2, (const char*)fb->buf, fb->len);
esp_http_client_set_header(client2, "Content-Disposition", "form-data; name=\"image\"; filename=\"image.jpg\"");
esp_err_t err2 = esp_http_client_perform(client2);
if (err2 != ESP_OK) {
Serial.printf("HTTP POST request failed with error %d", err2);
}
// Release the image buffer
esp_camera_fb_return(fb);
// Wait for a while before taking another photo
delay(5000);
}
在此示例中,我们使用 esp_camera 库从 ESP32-CAM 拍摄照片,然后使用 HTTPClient 库将图像作为'multipart/form-data' POST 请求上传到服务器。在上传之前,我们将'Content-Type' 标头设置为'multipart/form-data',并将图像数据设置为 POST 字段。然后,我们将'Content-Disposition' 标头设置为'form-data; name="image"; filename="image.jpg"',以指定表单数据的名称和文件名。最后,我们使用 esp_http_client 库执行 HTTP POST 请求,并检查错误代码以确保请求成功。
原文地址: https://www.cveoy.top/t/topic/jOdt 著作权归作者所有。请勿转载和采集!