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

时间:2013-01-28 20:43:29

标签: 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”。如何模拟提交“file_entry”与C cURL像html一样?我尝试使用CURLOPT_POSTFIELDS,但不起作用。

任何人都可以帮助我?

谢谢

1 个答案:

答案 0 :(得分:2)

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

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

或者,您可以更改服务器端。