尝试使用 HTTPClient 将图像文件发送到 PHP

Posted

技术标签:

【中文标题】尝试使用 HTTPClient 将图像文件发送到 PHP【英文标题】:Try to send image file to PHP with HTTPClient 【发布时间】:2019-04-15 07:18:30 【问题描述】:

我尝试在 esp32 上运行我的代码后得到了这个

注意:未定义索引:第 23 行 C:\xampp\htdocs\acc.php 中的 imageFile

我在 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\"\r\n");
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();

我可以使用此代码发送字符串,但我上面的代码不起作用 (cam.getfb() 返回 uint8_t 和 cam.getSize() 返回 size_t)

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

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 我尝试更新我的代码

<?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);
?>

【问题讨论】:

您不能只将单个表单元素作为有效负载。你首先需要Content-Type: multipart/form-data。然后嵌入您的图像条目。否则 PHP 将不会填充 $_FILES。 // 或者,您当然可以通过 php://input 访问文字 POST 正文,但不会有任何有效负载元信息 ($_FILES)。 请将您的解决方案移至自己的答案,谢谢。 您好,是否可以将MJPEG流也从Camera发送到PHP服务器并直接记录在服务器上? 【参考方案1】:

工作。

#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("\r\nHello 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("--\r\n");
  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("\r\n"+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.1\r\n");
      data += F("cache-control: no-cache\r\n");
      data += F("Content-Type: multipart/form-data; boundary=");
      data += BOUNDARY;
      data += "\r\n";
      data += F("User-Agent: PostmanRuntime/6.4.1\r\n");
      data += F("Accept: */*\r\n");
      data += F("Host: ");
      data += SERVER;
      data += F("\r\n");
      data += F("accept-encoding: gzip, deflate\r\n");
      data += F("Connection: keep-alive\r\n");
      data += F("content-length: ");
      data += String(length);
      data += "\r\n";
      data += "\r\n";
    return(data);

String body(String content , String message)

  String data;
  data = "--";
  data += BOUNDARY;
  data += F("\r\n");
  if(content=="imageFile")
  
    data += F("Content-Disposition: form-data; name=\"imageFile\"; filename=\"picture.jpg\"\r\n");
    data += F("Content-Type: image/jpeg\r\n");
    data += F("\r\n");
  
  else
  
    data += "Content-Disposition: form-data; name=\"" + content +"\"\r\n";
    data += "\r\n";
    data += message;
    data += "\r\n";
  
   return(data);

和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";
?>

【讨论】:

以上是关于尝试使用 HTTPClient 将图像文件发送到 PHP的主要内容,如果未能解决你的问题,请参考以下文章

使用HttpClient发送文件流到服务器端

在 c# HttpClient 4.5 中发布 multipart/form-data

如何使用 C# HttpClient 或 AWS SDK 通过 CloudFront 将视频上传到 S3

Android JSON HttpClient 使用 HttpResponse 将数据发送到 PHP 服务器

C# Xamarin 文件上传到 API 可以使用 RestSharp,但不能使用 HttpClient

使用java发送文件以形成帖子