在使用C語言進行編程時,有時需要接收上傳的JSON格式的圖片。下面通過一個示例代碼來介紹如何實現這一功能。
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <curl/curl.h> #define HTTP_FORM_BOUNDARY "--------------------------145817612720890910647490" #define UPLOAD_IMAGE_URL "http://example.com/upload" #define IMAGE_PATH "image.jpg" static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream) { FILE *file = (FILE*)stream; if (!file) return 0; return fread(ptr, size, nmemb, file); } int main(int argc, const char* argv[]) { CURL *curl = curl_easy_init(); CURLcode res; FILE *file = fopen(IMAGE_PATH, "rb"); if (!curl || !file) return -1; curl_easy_setopt(curl, CURLOPT_URL, UPLOAD_IMAGE_URL); curl_easy_setopt(curl, CURLOPT_POST, 1); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: multipart/form-data; boundary=" HTTP_FORM_BOUNDARY); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); fseek(file, 0, SEEK_END); long fileSize = ftell(file); rewind(file); char *payload = calloc(sizeof(char), fileSize + 2048); sprintf(payload, "--" HTTP_FORM_BOUNDARY "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" IMAGE_PATH "\"\r\nContent-Type: image/jpeg\r\n\r\n"); int offset = strlen(payload); fseek(file, 0, SEEK_SET); if (fileSize >fread(payload + offset, 1, fileSize, file)) { fclose(file); free(payload); return -3; } offset += fileSize; sprintf(payload + offset, "\r\n--" HTTP_FORM_BOUNDARY "--\r\n"); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, offset); curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); curl_easy_setopt(curl, CURLOPT_READDATA, file); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, stdout); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); curl_easy_cleanup(curl); free(payload); fclose(file); return res; }
這是一個使用CURL庫來實現的上傳圖片的示例,其中關鍵部分是如何拼接請求的payload。首先,設置請求的Content-Type為multipart/form-data,并指定分隔符。接著,讀取圖片的內容并將其拼接到payload中。最后,在curl_easy_setopt中指定讀取函數和寫入函數,然后使用curl_easy_perform執行請求即可。
上一篇python 特殊語法
下一篇python 的re模塊