php - 使用 POST 使用 curl 上传文件,但模拟 HTML 提交

标签 php c post curl libcurl

我有以下 C 代码:

int main(int argc, char* argv[])
{
  CURL *curl;
  CURLcode res;
  struct stat file_info;
  double speed_upload, total_time;
  FILE *fd;

  fd = fopen(argv[1], "rb"); /* open file to upload */
  if(!fd) {

    return 1; /* can't continue */
  }

  /* to get the file size */
  if(fstat(fileno(fd), &file_info) != 0) {

    return 1; /* can't continue */
  }

  curl = curl_easy_init();
  if(curl) {
    /* upload to this place */
    curl_easy_setopt(curl, CURLOPT_URL,
                     "http://www.website.com/index.php");

    /* tell it to "upload" to the URL */
    curl_easy_setopt(curl, CURLOPT_POST, 1L);

    /* set where to read from (on Windows you need to use READFUNCTION too) */
    curl_easy_setopt(curl, CURLOPT_READDATA, fd);

    /* and give the size of the upload (optional) */
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                     (curl_off_t)file_info.st_size);

    /* enable verbose for easier tracing */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    }
    else {
      /* now extract transfer info */
      curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &speed_upload);
      curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);

      fprintf(stderr, "Speed: %.3f bytes/sec during %.3f seconds\n",
              speed_upload, total_time);

    }
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  return 0;
}

和以下 PHP 代码:

<?php
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] == 'POST' )
{
    if( isset( $_FILES["file_entry"] ) )
    {
    print "file ok";
    }
    else
    {
    print "no file sent";
    }
}
else
{
    print "No post method" . $_SERVER['REQUEST_METHOD'];
}
?>

和html代码:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>
</head>
<body>
<form action="index.php" enctype="multipart/form-data" method="post">
    <input type="file" name="file_entry"/>
    <input type="submit" value="enviar"/>
</form>
</body>
</html>

如果我尝试通过 html 发送文件,它工作正常,但当我使用 C 和 cURL 时就不行了。 因为我不知道如何发送“file_entry”。我怎样才能像 html 那样用 C cURL 模拟提交“file_entry”?我尝试使用 CURLOPT_POSTFIELDS,但不起作用。

谁能帮帮我?

谢谢

最佳答案

这是因为您的服务器端需要一个“multipart/form-data”POST,而您发送了一个常规的“url-encoded”POST。

例如,您应该查看 multi-post.c示例或 curl_formadd () 文档。

或者您更改服务器端。

关于php - 使用 POST 使用 curl 上传文件,但模拟 HTML 提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14570880/

相关文章:

java - 将原始格式的数据发布到 PHP 文件并获取响应

ios - 通过 iOS 将数据发送到 POST JSON Web 服务

php - NetBeans 8.2 在 Ubuntu 17.04 上卡住

php - 不使用表单中的空字段更新数据库

php - 我的 PHP 脚本如何判断服务器是否繁忙?

将内容写入文件的 C 代码不起作用

java - 嵌套运行时异常 : Cannot parse POST parameters of request

php - cron 作业很昂贵吗?或者他们基本上是访问?

java - 手动安装JRE到用户电脑的步骤

c - 将节点追加到链表