天天看點

CURL 和LIBCURL C++代碼 上傳本地檔案,好不容易碰到了這種折騰我幾天的代碼

解決了什麼問題:curl在使用各種方式上傳檔案到伺服器。

伺服器端PHP代碼:

<?php

if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 200000)) {

    if ($_FILES["file"]["error"] > 0) {

        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    } else {

        if (file_exists("upload/" . $_FILES["file"]["name"])) {

            echo $_FILES["file"]["name"] . " already exists. ";

        } else {

            move_uploaded_file($_FILES["file"]["tmp_name"], "data/" . $_FILES["file"]["name"]);

            // echo "Stored in: " . "data/" . $_FILES["file"]["name"];

            echo "檔案上傳成功!";

        }

    }

} else {

    echo " 檔案無效!";

}

?>

用戶端送出的form:

<form action="upload.php" method="post" enctype="multipart/form-data">

                        <input type="file" name="file"/>

                        <input type="submit" class="btn btn-primary btn-large" value="上傳檔案" />

  </form>

在控制台使用curl上傳的例子:

curl -F "action=upload.php" -F "method=post" -F "file=@/Users/mark/xx.gif" http://ylg.zs108.com:8080/tmp/upload.php

使用libcurl實作的代碼:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <curl/curl.h>

#define POSTURL "http://ylg.zs108.com:8080/tmp/upload.php"

#define POSTFIELDS "?action=upload&method=post"

#define FILENAME "curlposttest.log"

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);

int main(int argc, char *argv[]) {

    CURL *curl;

    CURLcode res;

    FILE *fptr;

    struct curl_slist *http_header = NULL;

    if ((fptr = fopen(FILENAME, "w")) == NULL) {

        fprintf(stderr, "fopen file error: %s\n", FILENAME);

        exit(1);

    curl = curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

    curl_easy_setopt(curl, CURLOPT_WRITEDATA, fptr);

    struct curl_httppost *formpost = 0;

    struct curl_httppost *lastptr  = 0;

    curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "reqformat", CURLFORM_PTRCONTENTS, "plain", CURLFORM_END);

    curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "file", CURLFORM_FILE, "/Users/hanyanyan/xx.gif", CURLFORM_END);

    curl_easy_setopt(curl, CURLOPT_URL, POSTURL);

    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    res = curl_easy_perform(curl);

    curl_easy_cleanup(curl);

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) {

    FILE *fptr = (FILE*)userp;

    fwrite(buffer, size, nmemb, fptr);

}  

編譯方式:gcc -o curl_post_file filename.c -lcurl

後期調整:

<!DOCTYPE html>

<!-- saved from url=(0044)http://ylg.zs108.com:8080/dp/uploadtest.html -->

<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta charset="UTF-8">

        <title>Document</title>

    <style type="text/css"></style></head>

    <body>

        <div class="containter-fluid">

            <div class="row-fluid">

                <div class="span8 offset2">

                    <form action="http://ylg.zs108.com:8080/dp/upload.php" method="post" enctype="multipart/form-data">

                        <table cellpadding="10" border="1">

                            <tbody><tr>

                                <td>wid</td>

                                <td><input type="text" name="wid" value="dengpan"></td>

                            </tr>

                            <tr>

                                <td>text</td>

                                <td><input type="text" name="text" value="哈哈哈呵呵"></td>

                                <td>stime</td>

                                <td><input type="text" name="stime" value="13"></td>

                                <td>ssize</td>

                                <td><input type="text" name="ssize" value="15"></td>

                                <td>lid</td>

                                <td><input type="text" name="lid" value="2"></td>

                                <td>type</td>

                                <td><input type="text" name="type" value="2"></td>

                                <td>sound</td>

                                <td><input type="file" name="sound"></td>

                                <td></td>

                                <td><input type="submit" value="送出"></td>

                        </tbody></table>

                    </form>

                </div>

            </div>

        </div>

</body></html>

指令行:

curl -F "method=post" -F "action=upload.php" -F "wid=dengpan" -F "text=hh" -F "stime=13" -F "ssize=15" -F "lid=2" -F "type=2" -F "sound=@/Users/hanyanyan/million.amr" http://ylg.zs108.com:8080/dp/upload.php

傳回代碼:

{"code":1,"result":{"sound":"http:\/\/ylg.zs108.com:8080\/dp\/data\/sounds\/1378815106-a3864fc57553bf4b299b4d4c0ce07649.amr"}}

最後在貼一段PHP上傳的代碼吧

需要被上傳的檔案需要在檔案名前加上“@”以示區分,并且,檔案名需要是完整路徑。

以下php函數來模拟html表單的送出資料:

function uploadByCURL($post_data,$post_url){

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $post_url);

    curl_setopt($curl, CURLOPT_POST, 1 );

    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($curl,CURLOPT_USERAGENT,"Mozilla/4.0");

    $result = curl_exec($curl);

    $error = curl_error($curl);

    return $error ? $error : $result;

/*函數的使用:*/

$url = "http://127.0.0.1/app.php";

$data = array(

    "username" => $username,

    "password"  => $password,

    "file1"  => "@".realpath("photo1.jpg"),

    "file2"  => "@".realpath("file2.xml")

);

print_r(uploadByCURL($data,$url));