2014-04-22 7 views
0

저는 C++ 환경을 처음 사용합니다. C++에서 PHP 서버에 이미지 파일을 업로드하려고합니다. 하지만 전체 파일을 보내지는 않습니다. 업로드 한 이미지 파일 크기는 1KB입니다.C에서 이미지 파일 업로드

내 게시물이 너무 좋아. 하지만 이미지 binary를 base64 문자열로 변환하는 방법을 모르겠습니다. 내가 memcpy 다른 솔루션을 시도, 그것도 작동하지 않습니다.

Upload file via POST

내 C++ 코드 :

#define _CRT_SECURE_NO_DEPRECATE 
#include <iostream> 
#include <tchar.h> 
#include <Urlmon.h> 
#pragma comment (lib, "Urlmon.lib") 

#include <windows.h> 
#include <wininet.h> 
#include <iostream> 
#include <tchar.h> 
#include <stdio.h> 

#pragma comment(lib,"wininet.lib") 
#define ERROR_OPEN_FILE  10 
#define ERROR_MEMORY   11 
#define ERROR_SIZE   12 
#define ERROR_INTERNET_OPEN 13 
#define ERROR_INTERNET_CONN 14 
#define ERROR_INTERNET_REQ 15 
#define ERROR_INTERNET_SEND 16 

using namespace cv; 
using namespace std; 

int main() 
{ 
    // Local variables 
    static char *filename = "test.jpg"; //Filename to be loaded 
    static char *filepath = "test.jpg"; //Filename to be loaded 
    static char *type = "text/jpeg"; 
    static TCHAR hdrs[] = "Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858"; 
    static char boundary[] = "-----------------------------7d82751e2bc0858";   //Header boundary 
    static char nameForm[] = "uploadedfile";  //Input form name 
    static char iaddr[] = "server";  //IP address 
    static char url[] = "uploader.php"; 

    char * buffer;     //Buffer containing file + headers 
    char * content;     //Buffer containing file 
    FILE * pFile;     //File pointer 
    long lSize;      //File size 
    size_t result; 
    char *pos; // used in the loop 

    // Open file 
    pFile = fopen(filepath, "rb"); 
    if (pFile == NULL) 
    { 
     printf("ERROR_OPEN_FILE"); 
     getchar(); 
     return ERROR_OPEN_FILE; 
    } 
    printf("OPEN_FILE\n"); 

    // obtain file size: 
    fseek(pFile, 0, SEEK_END); 
    lSize = ftell(pFile); 
    rewind(pFile); 

    // allocate memory to contain the whole file: 
    content = (char*)malloc(sizeof(char)*lSize); 
    if (content == NULL) 
    { 
     printf("ERROR_MEMORY"); 
     getchar(); 
     return ERROR_OPEN_FILE; 
    } 

    printf("MEMORY_ALLOCATED\t \"%d\" \n", lSize); 
    // copy the file into the buffer: 
    result = fread(content, 1, lSize, pFile); 

    rewind (pFile); 

    if (result != lSize) 
    { 
     printf("ERROR_SIZE"); 
     getchar(); 
     return ERROR_OPEN_FILE; 
    } 
    printf("SIZE_OK\n"); 

    // terminate 
    fclose(pFile); 
    printf("FILE_CLOSE\n"); 
    //allocate memory to contain the whole file + HEADER 
    buffer = (char*)malloc(sizeof(char)*lSize + 2048); 

    //print header 
    sprintf(buffer, "%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n", boundary, nameForm, filename); 
    sprintf(buffer, "%sContent-Type: %s\r\n", buffer, type); 
    //sprintf(buffer, "%sContent-Length: %d\r\n", buffer, lSize); 
    sprintf(buffer, "%s\r\n%s\r\n", buffer, content); 

    /** 
    sprintf(buffer, "%s\r\n", buffer); 
    memcpy(buffer + strlen(buffer),content,lSize); 
    sprintf(buffer, "%s\r\n", buffer); 
    */ 
    sprintf(buffer, "%s%s--\r\n", buffer, boundary); 

    //Open internet connection 
    HINTERNET hSession = InternetOpen("WINDOWS", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); 
    if (hSession == NULL) 
    { 
     printf("ERROR_INTERNET_OPEN"); 
     getchar(); 
     return ERROR_OPEN_FILE; 
    } 
    printf("INTERNET_OPENED\n"); 

    HINTERNET hConnect = InternetConnect(hSession, iaddr, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1); 
    if (hConnect == NULL) 
    { 
     printf("ERROR_INTERNET_CONN"); 
     getchar(); 
     return ERROR_INTERNET_CONN; 
    } 
    printf("INTERNET_CONNECTED\n"); 

    HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST", _T(url), NULL, NULL, NULL, INTERNET_FLAG_RELOAD, 1); 
    if (hRequest == NULL) 
    { 
     printf("ERROR_INTERNET_REQ"); 
     getchar(); 

    } 
    printf("INTERNET_REQ_OPEN\n"); 

    BOOL sent = HttpSendRequest(hRequest, hdrs, strlen(hdrs), buffer, strlen(buffer)); 

    if (!sent) 
    { 
     printf("ERROR_INTERNET_SEND"); 
     getchar(); 
     return ERROR_INTERNET_CONN; 
    } 
    printf("INTERNET_SEND_OK\n"); 
    printf("\r\n%s\r\n",buffer); 

    //close any valid internet-handles 
    InternetCloseHandle(hSession); 
    InternetCloseHandle(hConnect); 
    InternetCloseHandle(hRequest); 
} 

출력 :

OPEN_FILE 
MEMORY_ALLOCATED  "44358" 
SIZE_OK 
FILE_CLOSE 
INTERNET_OPENED 
INTERNET_CONNECTED 
INTERNET_REQ_OPEN 
INTERNET_SEND_OK 


-----------------------------7d82751e2bc0858 

Content-Disposition: form-data; name="uploadedfile"; filename="test.jpg" 

Content-Type: text/jpeg 



ÿØÿà 

-----------------------------7d82751e2bc0858-- 

감사

+0

libcurl 등을 사용하지 않은 이유는 무엇입니까? – deviantfan

+1

내용이 문자열 인 것처럼 인쇄합니다. 즉 처음 0에서 멈추는 것을 의미합니다. – jsantander

+0

또한 항상 동일한 장소에서 전속력을 달리며 ... 버퍼 포인터를 앞으로 나아갈 필요가 있습니다 – jsantander

답변

1

당신은 바이너리 경로

로 유지하는 경우

대신 :

(210) 그러나 어떤 경우에 내 추천 즉 HTTP 통신을 구현하는 당신이 존재하는 많은 도서관의보고입니다

일부 추가 참고 사항 (libCURL를 시작하기에 좋은 장소입니다) 나 strlen으로

BOOL sent = HttpSendRequest(hRequest, hdrs, strlen(hdrs), buffer, strlen(buffer)); 

BOOL sent = HttpSendRequest(hRequest, hdrs, strlen(hdrs), buffer, chars); 

을 (버퍼)는 첫 번째 널 문자에서 멈출 것이다.

결과를 표준 출력으로 출력하면 문자열 ....로 처리되고 첫 번째 null로 끝납니다.

+0

안녕하세요, 귀하의 코드를 시도했지만 바이너리를 두 번 인쇄합니다. '----------------------------- 7d82751e2bc0858 콘텐츠 - 처분 : form-data; name = "uploadedfile"; filename = "테스트.JPG " 콘텐츠 유형 : 텍스트/JPEG 콘텐츠 길이 : 44,358 ÿØÿà ÿØÿà ' –

+0

죄송합니다 ... 나는 ... 잘라 버전을 붙여 넣기하고 memcopy 부분의 주석을했지만, 하나의 sprintf를 제거하는 것을 잊었습니다 .... 지금 확인 하시겠습니까? – jsantander

+0

버퍼에 끝 경계를 인쇄하지 않습니다. 이미지 바이너리도 같은 값입니다. 전체 파일을 읽지 않습니다. –