ESP32 Try to send image file to php with HTTPClient












1














I got this after I try to running my code on esp32




Notice: Undefined index: imageFile in C:xampphtdocsacc.php on line 23




My code on esp32



HTTPClient http;
http.begin("http://192.168.43.86/acc.php"); //Specify destination for HTTP request
http.addHeader("Content-Disposition", "form-data; name="imageFile"; filename="picture.jpg"rn");
http.addHeader("Content-type", "image/jpeg");

int httpResponseCode = http.POST(cam.getfb(), cam.getSize());


if (httpResponseCode > 0) {

String response = http.getString(); //Get the response to the request

Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer

} else {

Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);

}

http.end();


I can send String by using this code but my code above don't work
(cam.getfb() return as uint8_t and cam.getSize() return as size_t)



  http.addHeader("Content-type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST("word=" + Cword);


code in php



<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageFile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(1) {
$check = getimagesize($_FILES["imageFile"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["imageFile"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["imageFile"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageFile"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>


11/13/2018 I try to update my code



<?php
date_default_timezone_set("Asia/Bangkok");
$date = date("Y_m_d_h_i_s");
$directory = "http://192.168.43.192/capture.jpg";
$data = $rawData = file_get_contents("php://input");
$new = "images/".$date.".jpg";
file_put_contents($new, $data);
?>




Solved



WORK.



#include "WiFiClientSecure.h"
#include "Camera_Exp.h"
CAMERA cam;
char ssid = "";
char pass = "";
#define SENSOR 19
#define SERVER ""
#define PORT 443
#define BOUNDARY "--------------------------133747188241686651551404"
#define TIMEOUT 20000

void setup()
{
pinMode(SENSOR,INPUT);
Serial.begin(115200);
Serial.println("rnHello Line Notify");
cam.setFrameSize(CAMERA_FS_QVGA);
cam.setMirror(false);
cam.setVflip(false);
cam.setWhiteBalance(true);
esp_err_t err = cam.init();
if (err != ESP_OK)
{
Serial.println("Camera init failed with error =" + String( err));
return;
}
WiFi.begin(ssid, pass);
unsigned char led_cnt=0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void loop()
{
while(!digitalRead(SENSOR)){
Serial.println("Undetect");
}
String res;
if(digitalRead(SENSOR))
{
Serial.println("Send Picture");
esp_err_t err;
err = cam.capture();
if (err == ESP_OK)
{
res = sendImage("asdw","A54S89EF5",cam.getfb(),cam.getSize());
Serial.println(res);
}
else
Serial.println("Camera Error");

while(digitalRead(SENSOR));
}
}

//////

String sendImage(String token,String message, uint8_t *data_pic,size_t size_pic)
{
String bodyTxt = body("message",message);
String bodyPic = body("imageFile",message);
String bodyEnd = String("--")+BOUNDARY+String("--rn");
size_t allLen = bodyTxt.length()+bodyPic.length()+size_pic+bodyEnd.length();
String headerTxt = header(token,allLen);
WiFiClientSecure client;
if (!client.connect(SERVER,PORT))
{
return("connection failed");
}

client.print(headerTxt+bodyTxt+bodyPic);
client.write(data_pic,size_pic);
client.print("rn"+bodyEnd);

delay(20);
long tOut = millis() + TIMEOUT;
while(client.connected() && tOut > millis())
{
if (client.available())
{
String serverRes = client.readStringUntil('r');
return(serverRes);
}
}
}
String header(String token,size_t length)
{
String data;
data = F("POST /ln/bot.php HTTP/1.1rn");
data += F("cache-control: no-cachern");
data += F("Content-Type: multipart/form-data; boundary=");
data += BOUNDARY;
data += "rn";
data += F("User-Agent: PostmanRuntime/6.4.1rn");
data += F("Accept: */*rn");
data += F("Host: ");
data += SERVER;
data += F("rn");
data += F("accept-encoding: gzip, deflatern");
data += F("Connection: keep-alivern");
data += F("content-length: ");
data += String(length);
data += "rn";
data += "rn";
return(data);
}
String body(String content , String message)
{
String data;
data = "--";
data += BOUNDARY;
data += F("rn");
if(content=="imageFile")
{
data += F("Content-Disposition: form-data; name="imageFile"; filename="picture.jpg"rn");
data += F("Content-Type: image/jpegrn");
data += F("rn");
}
else
{
data += "Content-Disposition: form-data; name="" + content +""rn";
data += "rn";
data += message;
data += "rn";
}
return(data);
}


and php



<?php
$uploadfile = "";
echo "Uploading ";
echo $_FILES["imageFile"]["name"];
if(strlen(basename($_FILES["imageFile"]["name"])) > 0)
{
$uploadfile = basename($_FILES["imageFile"]["name"]);
if(move_uploaded_file($_FILES["imageFile"]["tmp_name"], $uploadfile))
{
@chmod($uploadfile,0777); echo " Ok! ";
$datum = mktime(date('H')+0, date('i'), date('s'), date('m'), date('d'), date('y'));
if (file_exists("old/".date('Y_m_d', $datum) )) {
print("Directory already exists.n");
} else {
mkdir("old/".date('Y_m_d', $datum));
copy("index1.php","old/".date('Y_m_d', $datum)."/index.php");
print("Directory creating.n");
}
echo "saved ";
copy($uploadfile,"old/".date('Y_m_d', $datum)."/".date('Y.m.d_H-i-s', $datum).".jpg");
}
else echo " Error copying!";
}
echo date('Y.m.d_H:i', $datum);
echo "status = DONE";
?>









share|improve this question
























  • You can't just put a single form element as payload. You need Content-Type: multipart/form-data first. Then embed your image entry. Else PHP won't populate $_FILES. // Alternatively you could access a literal POST body via php://input of course, but wouldn't have any payload meta info ($_FILES) then.
    – mario
    Nov 12 '18 at 14:50










  • Please move your solution to an answer of its own, thank you.
    – Cœur
    Dec 31 '18 at 8:20
















1














I got this after I try to running my code on esp32




Notice: Undefined index: imageFile in C:xampphtdocsacc.php on line 23




My code on esp32



HTTPClient http;
http.begin("http://192.168.43.86/acc.php"); //Specify destination for HTTP request
http.addHeader("Content-Disposition", "form-data; name="imageFile"; filename="picture.jpg"rn");
http.addHeader("Content-type", "image/jpeg");

int httpResponseCode = http.POST(cam.getfb(), cam.getSize());


if (httpResponseCode > 0) {

String response = http.getString(); //Get the response to the request

Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer

} else {

Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);

}

http.end();


I can send String by using this code but my code above don't work
(cam.getfb() return as uint8_t and cam.getSize() return as size_t)



  http.addHeader("Content-type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST("word=" + Cword);


code in php



<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageFile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(1) {
$check = getimagesize($_FILES["imageFile"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["imageFile"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["imageFile"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageFile"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>


11/13/2018 I try to update my code



<?php
date_default_timezone_set("Asia/Bangkok");
$date = date("Y_m_d_h_i_s");
$directory = "http://192.168.43.192/capture.jpg";
$data = $rawData = file_get_contents("php://input");
$new = "images/".$date.".jpg";
file_put_contents($new, $data);
?>




Solved



WORK.



#include "WiFiClientSecure.h"
#include "Camera_Exp.h"
CAMERA cam;
char ssid = "";
char pass = "";
#define SENSOR 19
#define SERVER ""
#define PORT 443
#define BOUNDARY "--------------------------133747188241686651551404"
#define TIMEOUT 20000

void setup()
{
pinMode(SENSOR,INPUT);
Serial.begin(115200);
Serial.println("rnHello Line Notify");
cam.setFrameSize(CAMERA_FS_QVGA);
cam.setMirror(false);
cam.setVflip(false);
cam.setWhiteBalance(true);
esp_err_t err = cam.init();
if (err != ESP_OK)
{
Serial.println("Camera init failed with error =" + String( err));
return;
}
WiFi.begin(ssid, pass);
unsigned char led_cnt=0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void loop()
{
while(!digitalRead(SENSOR)){
Serial.println("Undetect");
}
String res;
if(digitalRead(SENSOR))
{
Serial.println("Send Picture");
esp_err_t err;
err = cam.capture();
if (err == ESP_OK)
{
res = sendImage("asdw","A54S89EF5",cam.getfb(),cam.getSize());
Serial.println(res);
}
else
Serial.println("Camera Error");

while(digitalRead(SENSOR));
}
}

//////

String sendImage(String token,String message, uint8_t *data_pic,size_t size_pic)
{
String bodyTxt = body("message",message);
String bodyPic = body("imageFile",message);
String bodyEnd = String("--")+BOUNDARY+String("--rn");
size_t allLen = bodyTxt.length()+bodyPic.length()+size_pic+bodyEnd.length();
String headerTxt = header(token,allLen);
WiFiClientSecure client;
if (!client.connect(SERVER,PORT))
{
return("connection failed");
}

client.print(headerTxt+bodyTxt+bodyPic);
client.write(data_pic,size_pic);
client.print("rn"+bodyEnd);

delay(20);
long tOut = millis() + TIMEOUT;
while(client.connected() && tOut > millis())
{
if (client.available())
{
String serverRes = client.readStringUntil('r');
return(serverRes);
}
}
}
String header(String token,size_t length)
{
String data;
data = F("POST /ln/bot.php HTTP/1.1rn");
data += F("cache-control: no-cachern");
data += F("Content-Type: multipart/form-data; boundary=");
data += BOUNDARY;
data += "rn";
data += F("User-Agent: PostmanRuntime/6.4.1rn");
data += F("Accept: */*rn");
data += F("Host: ");
data += SERVER;
data += F("rn");
data += F("accept-encoding: gzip, deflatern");
data += F("Connection: keep-alivern");
data += F("content-length: ");
data += String(length);
data += "rn";
data += "rn";
return(data);
}
String body(String content , String message)
{
String data;
data = "--";
data += BOUNDARY;
data += F("rn");
if(content=="imageFile")
{
data += F("Content-Disposition: form-data; name="imageFile"; filename="picture.jpg"rn");
data += F("Content-Type: image/jpegrn");
data += F("rn");
}
else
{
data += "Content-Disposition: form-data; name="" + content +""rn";
data += "rn";
data += message;
data += "rn";
}
return(data);
}


and php



<?php
$uploadfile = "";
echo "Uploading ";
echo $_FILES["imageFile"]["name"];
if(strlen(basename($_FILES["imageFile"]["name"])) > 0)
{
$uploadfile = basename($_FILES["imageFile"]["name"]);
if(move_uploaded_file($_FILES["imageFile"]["tmp_name"], $uploadfile))
{
@chmod($uploadfile,0777); echo " Ok! ";
$datum = mktime(date('H')+0, date('i'), date('s'), date('m'), date('d'), date('y'));
if (file_exists("old/".date('Y_m_d', $datum) )) {
print("Directory already exists.n");
} else {
mkdir("old/".date('Y_m_d', $datum));
copy("index1.php","old/".date('Y_m_d', $datum)."/index.php");
print("Directory creating.n");
}
echo "saved ";
copy($uploadfile,"old/".date('Y_m_d', $datum)."/".date('Y.m.d_H-i-s', $datum).".jpg");
}
else echo " Error copying!";
}
echo date('Y.m.d_H:i', $datum);
echo "status = DONE";
?>









share|improve this question
























  • You can't just put a single form element as payload. You need Content-Type: multipart/form-data first. Then embed your image entry. Else PHP won't populate $_FILES. // Alternatively you could access a literal POST body via php://input of course, but wouldn't have any payload meta info ($_FILES) then.
    – mario
    Nov 12 '18 at 14:50










  • Please move your solution to an answer of its own, thank you.
    – Cœur
    Dec 31 '18 at 8:20














1












1








1







I got this after I try to running my code on esp32




Notice: Undefined index: imageFile in C:xampphtdocsacc.php on line 23




My code on esp32



HTTPClient http;
http.begin("http://192.168.43.86/acc.php"); //Specify destination for HTTP request
http.addHeader("Content-Disposition", "form-data; name="imageFile"; filename="picture.jpg"rn");
http.addHeader("Content-type", "image/jpeg");

int httpResponseCode = http.POST(cam.getfb(), cam.getSize());


if (httpResponseCode > 0) {

String response = http.getString(); //Get the response to the request

Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer

} else {

Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);

}

http.end();


I can send String by using this code but my code above don't work
(cam.getfb() return as uint8_t and cam.getSize() return as size_t)



  http.addHeader("Content-type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST("word=" + Cword);


code in php



<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageFile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(1) {
$check = getimagesize($_FILES["imageFile"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["imageFile"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["imageFile"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageFile"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>


11/13/2018 I try to update my code



<?php
date_default_timezone_set("Asia/Bangkok");
$date = date("Y_m_d_h_i_s");
$directory = "http://192.168.43.192/capture.jpg";
$data = $rawData = file_get_contents("php://input");
$new = "images/".$date.".jpg";
file_put_contents($new, $data);
?>




Solved



WORK.



#include "WiFiClientSecure.h"
#include "Camera_Exp.h"
CAMERA cam;
char ssid = "";
char pass = "";
#define SENSOR 19
#define SERVER ""
#define PORT 443
#define BOUNDARY "--------------------------133747188241686651551404"
#define TIMEOUT 20000

void setup()
{
pinMode(SENSOR,INPUT);
Serial.begin(115200);
Serial.println("rnHello Line Notify");
cam.setFrameSize(CAMERA_FS_QVGA);
cam.setMirror(false);
cam.setVflip(false);
cam.setWhiteBalance(true);
esp_err_t err = cam.init();
if (err != ESP_OK)
{
Serial.println("Camera init failed with error =" + String( err));
return;
}
WiFi.begin(ssid, pass);
unsigned char led_cnt=0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void loop()
{
while(!digitalRead(SENSOR)){
Serial.println("Undetect");
}
String res;
if(digitalRead(SENSOR))
{
Serial.println("Send Picture");
esp_err_t err;
err = cam.capture();
if (err == ESP_OK)
{
res = sendImage("asdw","A54S89EF5",cam.getfb(),cam.getSize());
Serial.println(res);
}
else
Serial.println("Camera Error");

while(digitalRead(SENSOR));
}
}

//////

String sendImage(String token,String message, uint8_t *data_pic,size_t size_pic)
{
String bodyTxt = body("message",message);
String bodyPic = body("imageFile",message);
String bodyEnd = String("--")+BOUNDARY+String("--rn");
size_t allLen = bodyTxt.length()+bodyPic.length()+size_pic+bodyEnd.length();
String headerTxt = header(token,allLen);
WiFiClientSecure client;
if (!client.connect(SERVER,PORT))
{
return("connection failed");
}

client.print(headerTxt+bodyTxt+bodyPic);
client.write(data_pic,size_pic);
client.print("rn"+bodyEnd);

delay(20);
long tOut = millis() + TIMEOUT;
while(client.connected() && tOut > millis())
{
if (client.available())
{
String serverRes = client.readStringUntil('r');
return(serverRes);
}
}
}
String header(String token,size_t length)
{
String data;
data = F("POST /ln/bot.php HTTP/1.1rn");
data += F("cache-control: no-cachern");
data += F("Content-Type: multipart/form-data; boundary=");
data += BOUNDARY;
data += "rn";
data += F("User-Agent: PostmanRuntime/6.4.1rn");
data += F("Accept: */*rn");
data += F("Host: ");
data += SERVER;
data += F("rn");
data += F("accept-encoding: gzip, deflatern");
data += F("Connection: keep-alivern");
data += F("content-length: ");
data += String(length);
data += "rn";
data += "rn";
return(data);
}
String body(String content , String message)
{
String data;
data = "--";
data += BOUNDARY;
data += F("rn");
if(content=="imageFile")
{
data += F("Content-Disposition: form-data; name="imageFile"; filename="picture.jpg"rn");
data += F("Content-Type: image/jpegrn");
data += F("rn");
}
else
{
data += "Content-Disposition: form-data; name="" + content +""rn";
data += "rn";
data += message;
data += "rn";
}
return(data);
}


and php



<?php
$uploadfile = "";
echo "Uploading ";
echo $_FILES["imageFile"]["name"];
if(strlen(basename($_FILES["imageFile"]["name"])) > 0)
{
$uploadfile = basename($_FILES["imageFile"]["name"]);
if(move_uploaded_file($_FILES["imageFile"]["tmp_name"], $uploadfile))
{
@chmod($uploadfile,0777); echo " Ok! ";
$datum = mktime(date('H')+0, date('i'), date('s'), date('m'), date('d'), date('y'));
if (file_exists("old/".date('Y_m_d', $datum) )) {
print("Directory already exists.n");
} else {
mkdir("old/".date('Y_m_d', $datum));
copy("index1.php","old/".date('Y_m_d', $datum)."/index.php");
print("Directory creating.n");
}
echo "saved ";
copy($uploadfile,"old/".date('Y_m_d', $datum)."/".date('Y.m.d_H-i-s', $datum).".jpg");
}
else echo " Error copying!";
}
echo date('Y.m.d_H:i', $datum);
echo "status = DONE";
?>









share|improve this question















I got this after I try to running my code on esp32




Notice: Undefined index: imageFile in C:xampphtdocsacc.php on line 23




My code on esp32



HTTPClient http;
http.begin("http://192.168.43.86/acc.php"); //Specify destination for HTTP request
http.addHeader("Content-Disposition", "form-data; name="imageFile"; filename="picture.jpg"rn");
http.addHeader("Content-type", "image/jpeg");

int httpResponseCode = http.POST(cam.getfb(), cam.getSize());


if (httpResponseCode > 0) {

String response = http.getString(); //Get the response to the request

Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer

} else {

Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);

}

http.end();


I can send String by using this code but my code above don't work
(cam.getfb() return as uint8_t and cam.getSize() return as size_t)



  http.addHeader("Content-type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST("word=" + Cword);


code in php



<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageFile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(1) {
$check = getimagesize($_FILES["imageFile"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["imageFile"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["imageFile"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageFile"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>


11/13/2018 I try to update my code



<?php
date_default_timezone_set("Asia/Bangkok");
$date = date("Y_m_d_h_i_s");
$directory = "http://192.168.43.192/capture.jpg";
$data = $rawData = file_get_contents("php://input");
$new = "images/".$date.".jpg";
file_put_contents($new, $data);
?>




Solved



WORK.



#include "WiFiClientSecure.h"
#include "Camera_Exp.h"
CAMERA cam;
char ssid = "";
char pass = "";
#define SENSOR 19
#define SERVER ""
#define PORT 443
#define BOUNDARY "--------------------------133747188241686651551404"
#define TIMEOUT 20000

void setup()
{
pinMode(SENSOR,INPUT);
Serial.begin(115200);
Serial.println("rnHello Line Notify");
cam.setFrameSize(CAMERA_FS_QVGA);
cam.setMirror(false);
cam.setVflip(false);
cam.setWhiteBalance(true);
esp_err_t err = cam.init();
if (err != ESP_OK)
{
Serial.println("Camera init failed with error =" + String( err));
return;
}
WiFi.begin(ssid, pass);
unsigned char led_cnt=0;
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void loop()
{
while(!digitalRead(SENSOR)){
Serial.println("Undetect");
}
String res;
if(digitalRead(SENSOR))
{
Serial.println("Send Picture");
esp_err_t err;
err = cam.capture();
if (err == ESP_OK)
{
res = sendImage("asdw","A54S89EF5",cam.getfb(),cam.getSize());
Serial.println(res);
}
else
Serial.println("Camera Error");

while(digitalRead(SENSOR));
}
}

//////

String sendImage(String token,String message, uint8_t *data_pic,size_t size_pic)
{
String bodyTxt = body("message",message);
String bodyPic = body("imageFile",message);
String bodyEnd = String("--")+BOUNDARY+String("--rn");
size_t allLen = bodyTxt.length()+bodyPic.length()+size_pic+bodyEnd.length();
String headerTxt = header(token,allLen);
WiFiClientSecure client;
if (!client.connect(SERVER,PORT))
{
return("connection failed");
}

client.print(headerTxt+bodyTxt+bodyPic);
client.write(data_pic,size_pic);
client.print("rn"+bodyEnd);

delay(20);
long tOut = millis() + TIMEOUT;
while(client.connected() && tOut > millis())
{
if (client.available())
{
String serverRes = client.readStringUntil('r');
return(serverRes);
}
}
}
String header(String token,size_t length)
{
String data;
data = F("POST /ln/bot.php HTTP/1.1rn");
data += F("cache-control: no-cachern");
data += F("Content-Type: multipart/form-data; boundary=");
data += BOUNDARY;
data += "rn";
data += F("User-Agent: PostmanRuntime/6.4.1rn");
data += F("Accept: */*rn");
data += F("Host: ");
data += SERVER;
data += F("rn");
data += F("accept-encoding: gzip, deflatern");
data += F("Connection: keep-alivern");
data += F("content-length: ");
data += String(length);
data += "rn";
data += "rn";
return(data);
}
String body(String content , String message)
{
String data;
data = "--";
data += BOUNDARY;
data += F("rn");
if(content=="imageFile")
{
data += F("Content-Disposition: form-data; name="imageFile"; filename="picture.jpg"rn");
data += F("Content-Type: image/jpegrn");
data += F("rn");
}
else
{
data += "Content-Disposition: form-data; name="" + content +""rn";
data += "rn";
data += message;
data += "rn";
}
return(data);
}


and php



<?php
$uploadfile = "";
echo "Uploading ";
echo $_FILES["imageFile"]["name"];
if(strlen(basename($_FILES["imageFile"]["name"])) > 0)
{
$uploadfile = basename($_FILES["imageFile"]["name"]);
if(move_uploaded_file($_FILES["imageFile"]["tmp_name"], $uploadfile))
{
@chmod($uploadfile,0777); echo " Ok! ";
$datum = mktime(date('H')+0, date('i'), date('s'), date('m'), date('d'), date('y'));
if (file_exists("old/".date('Y_m_d', $datum) )) {
print("Directory already exists.n");
} else {
mkdir("old/".date('Y_m_d', $datum));
copy("index1.php","old/".date('Y_m_d', $datum)."/index.php");
print("Directory creating.n");
}
echo "saved ";
copy($uploadfile,"old/".date('Y_m_d', $datum)."/".date('Y.m.d_H-i-s', $datum).".jpg");
}
else echo " Error copying!";
}
echo date('Y.m.d_H:i', $datum);
echo "status = DONE";
?>






php c http arduino esp32






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 31 '18 at 8:20









Cœur

17.4k9103145




17.4k9103145










asked Nov 12 '18 at 14:34









Mark Puttipong

62




62












  • You can't just put a single form element as payload. You need Content-Type: multipart/form-data first. Then embed your image entry. Else PHP won't populate $_FILES. // Alternatively you could access a literal POST body via php://input of course, but wouldn't have any payload meta info ($_FILES) then.
    – mario
    Nov 12 '18 at 14:50










  • Please move your solution to an answer of its own, thank you.
    – Cœur
    Dec 31 '18 at 8:20


















  • You can't just put a single form element as payload. You need Content-Type: multipart/form-data first. Then embed your image entry. Else PHP won't populate $_FILES. // Alternatively you could access a literal POST body via php://input of course, but wouldn't have any payload meta info ($_FILES) then.
    – mario
    Nov 12 '18 at 14:50










  • Please move your solution to an answer of its own, thank you.
    – Cœur
    Dec 31 '18 at 8:20
















You can't just put a single form element as payload. You need Content-Type: multipart/form-data first. Then embed your image entry. Else PHP won't populate $_FILES. // Alternatively you could access a literal POST body via php://input of course, but wouldn't have any payload meta info ($_FILES) then.
– mario
Nov 12 '18 at 14:50




You can't just put a single form element as payload. You need Content-Type: multipart/form-data first. Then embed your image entry. Else PHP won't populate $_FILES. // Alternatively you could access a literal POST body via php://input of course, but wouldn't have any payload meta info ($_FILES) then.
– mario
Nov 12 '18 at 14:50












Please move your solution to an answer of its own, thank you.
– Cœur
Dec 31 '18 at 8:20




Please move your solution to an answer of its own, thank you.
– Cœur
Dec 31 '18 at 8:20












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264373%2fesp32-try-to-send-image-file-to-php-with-httpclient%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53264373%2fesp32-try-to-send-image-file-to-php-with-httpclient%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Hercules Kyvelos

Tangent Lines Diagram Along Smooth Curve

Yusuf al-Mu'taman ibn Hud