Sending pictures via http with an ESP32-CAM
Sending pictures via http with an ESP32-CAM
Pictures taken with the ESP32-CAM can be sent in a multipart/form-data type content via HTTP. Here is a sample code to achieve this:
#define BOUNDARY "--------------------------133747188241686651551404"
#define API_ROUTE "/upload"
#define API_HOST "192.168.1.2"
#define API_PORT 80
void upload_image(){
// Get a frame
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if (fb) {
// Frame was taken successfully, now sending it
// Define the client that will be used for the API call
WiFiClient client;
// Attempt a connection
if (client.connect(API_HOST, API_PORT)) {
// Connection was successful, prepare the request content
String body_pre_image;
body_pre_image = "--";
body_pre_image += BOUNDARY;
body_pre_image += "\r\n";
body_pre_image += "Content-Disposition: form-data; name=\"imageFile\"; filename=\"picture.jpg\"\r\n");
body_pre_image += "Content-Type: image/jpeg\r\n";
body_pre_image += "\r\n";
String body_post_image = String("\r\n--")+BOUNDARY+String("--\r\n");
int total_length = body_pre_image.length()+body_post_image.length()+fb->len;
String header_text;
header_text = "POST " + String(API_ROUTE) + " HTTP/1.1\r\n"; // the method is defined here
header_text += "cache-control: no-cache\r\n";
header_text += "Content-Type: multipart/form-data; boundary=";
header_text += BOUNDARY;
header_text += "\r\n";
header_text += "content-length: ";
header_text += String(total_length);
header_text += "\r\n";
header_text += "\r\n";
// Now send the whole thing
client.print(header_text+body_pre_image);
client.write(fb->buf, fb->len);
client.print(body_post_image);
// timeout management
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println("Timeout");
client.stop();
break;
}
}
}
// No matter the result of the upload, clean up the frame buffer
esp_camera_fb_return(fb);
fb = NULL;
}
}