WinHttpRequest上传文件

问题描述 投票:0回答:1

我试图使用WinHttpRequest上传文件,但它不工作。

我做的一个cordova应用程序中的PHP文件正在工作。

我不知道还能做什么。

任何人都可以帮助。

谢谢。

VFP代码。

filecontent = FileToStr(ficheiro)

loHTTP = CREATEOBJECT("WinHttp.WinHttpRequest.5.1")    
loHTTP.Open("POST", "http://-----.com/webspace/upload.php", .F.)
loHTTP.SetRequestHeader("content-type", "text/plain") 

varrequest  = 'attachment; filename="' + JUSTFNAME(ficheiro) + '"'
loHTTP.SetRequestHeader("content-disposition", varrequest)

loHTTP.Send(filecontent)
WAIT WINDOW loHTTP.status 

upload.php中的代码。

<?php
$uploaddir = 'upload/';
$uploadfile = $uploaddir . $_FILES['file']['name'];

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    echo "File successfully uploaded.\n";
}

&gt;

PHP错误。

[12-Dec-2018 12:28:02 UTC] PHP Notice:  Undefined index: file in /home/webspace/upload.php on line 3
[12-Dec-2018 12:28:02 UTC] PHP Notice:  Undefined index: file in /home/webspace/upload.php on line 5




我修改了代码,现在我得到的文件是 "HTTP_RAW_POST_DATA",当我在PHP中做一个var_dump的时候

当前代码。

    loHTTP = CREATEOBJECT("WinHttp.WinHttpRequest.5.1")    
    loHTTP.Open("POST", "http://www.----------.com/webspace/getfile.php", .F.)
    xBOUNDARY   = "+++++"
    vbCrLf      = CHR(10) + CHR(13)

    filecontent = "--" + xBOUNDARY + vbCrLf
    filecontent = filecontent + 'Content-Disposition: form-data; name="file"; filename="' + JUSTFNAME(ficheiro) + '"' + vbCrLf
    filecontent = filecontent + "Content-type: text/plain" + vbCrLf + vbCrLf
    filecontent = filecontent + FileToStr(ficheiro)
    filecontent = filecontent + vbCrLf
    filecontent = filecontent + "--" + xBOUNDARY + "--"
    filecontent = filecontent + vbCrLf

    loHTTP.SetRequestHeader("CONTENT_TYPE", "multipart/form-data; boundary=" + xBOUNDARY + vbCrLf)
    loHTTP.SetRequestHeader("CONTENT_NAME", JUSTFNAME(ficheiro) + vbCrLf)

    loHTTP.Send(filecontent) 

在PHP中的var_dump。

array(7) {
  ["HTTP_RAW_POST_DATA"]=>
  string(245) "--+++++

Content-Disposition: form-data; name="file"; filename="Oo2Teste.txt"

Content-type: text/plain


00000000000000|00000000000000| BASE|00|GERAL|00|00
1.1|1.1|Leiria - PD Azambuja - CMR1|00|GERAL|00|00
T|T|TESTE|00|GERAL|00|00


--+++++--

"
  ["_GET"]=>
  array(0) {
  }
  ["_POST"]=>
  array(0) {
  }
  ["_COOKIE"]=>
  array(0) {
  }
  ["_FILES"]=>
  array(0) {
  }
  ["_SERVER"]=>
  array(38) {
    ["PATH"]=>
    string(28) "/usr/local/bin:/usr/bin:/bin"
    ["TEMP"]=>
    string(4) "/tmp"
    ["TMP"]=>
    string(4) "/tmp"
    ["TMPDIR"]=>
    string(4) "/tmp"
    ["PWD"]=>
    string(1) "/"
    ["HTTP_ACCEPT"]=>
    string(3) "*/*"
    ["HTTP_CONNECTION"]=>
    string(10) "Keep-Alive"
    ["CONTENT_TYPE"]=>
    string(25) "text/plain; Charset=UTF-8"
    ["CONTENT_LENGTH"]=>
    string(5) "20341"
    ["HTTP_USER_AGENT"]=>
    string(57) "Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)"
    ["HTTP_CONTENT_TYPE"]=>
    string(35) "multipart/form-data; boundary=+++++"
    ["HTTP_CONTENT_NAME"]=>
    string(14) "Oo2Teste.txt"
    ["UNIQUE_ID"]=>
    string(27) "XBI5X4NTz1un6WhRwU29ewAAAM0"
    ["gzip-only-text/html"]=>
    string(1) "1"
    ["SERVER_SIGNATURE"]=>
    string(0) ""
    ["SERVER_SOFTWARE"]=>
    string(6) "Apache"
    ["SERVER_PROTOCOL"]=>
    string(8) "HTTP/1.1"
    ["REQUEST_METHOD"]=>
    string(4) "POST"
    ["QUERY_STRING"]=>
    string(0) ""
    ["REQUEST_TIME_FLOAT"]=>
    float(1544698207.5962)
    ["REQUEST_TIME"]=>
    int(1544698207)
  }
  ["GLOBALS"]=>
  *RECURSION*
} 
php visual-foxpro winhttprequest
1个回答
0
投票

下面的工作对我来说,使用C Win 32 HTTP APIs。我上传两个文件的内容到一个HTTP监听器。

#include <Windows.h>
#include <winhttp.h>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

std::wstring ErrorMessage(DWORD dwMessageId)
{
    HMODULE h = GetModuleHandle(L"Winhttp");
    constexpr DWORD dwSize = 512;
    HANDLE hHeap = GetProcessHeap();
    LPWSTR lpwszBuffer = static_cast<LPWSTR>(HeapAlloc(hHeap, 0, dwSize * sizeof(WCHAR)));
    if (lpwszBuffer) {
        if (0 == FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, h, dwMessageId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpwszBuffer, dwSize, nullptr))
            _ltow_s(dwMessageId, lpwszBuffer, dwSize, 16);
        else {
            for (WCHAR* p; (p = wcschr(lpwszBuffer, L'\r')) != nullptr; *p = L' ') {}
            for (WCHAR* p; (p = wcschr(lpwszBuffer, L'\n')) != nullptr; *p = L' ') {}
        }

        std::wstring wsError = lpwszBuffer;
        HeapFree(hHeap, 0, lpwszBuffer);
        return wsError;
    }
    return std::wstring{};
}

std::wstring ContentLength(const size_t len)
{
    std::wstring str = L"Content-Length:" + std::to_wstring(len) + L"\r\n"s;

    return str;
    //return replace(str, L"%LENGTH%"s, std::to_wstring(len));
}

int main()
{
    DWORD dwSize = 0;
    LPVOID lpOutBuffer = NULL;
    BOOL  bResults = FALSE;
    HINTERNET hSession = NULL,
        hConnect = NULL,
        hRequest = NULL;

    std::ifstream in("ApplLog.txt");
    std::stringstream buffer;
    buffer << in.rdbuf();
    std::string applContents(buffer.str());

    std::ifstream inSystemLog("SystemLog.txt");
    std::stringstream sysBuffer;
    sysBuffer << inSystemLog.rdbuf();
    std::string systemContents(sysBuffer.str());

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"A WinHTTP Example Program/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    std::wstring url{ L"http://app.pomdit.com:3010/uploadfile" };
    URL_COMPONENTS components{};
    components.dwStructSize = sizeof(components);
    components.dwHostNameLength = (DWORD)-1;
    components.dwUrlPathLength = (DWORD)-1;
    if (!WinHttpCrackUrl(url.c_str(), static_cast<DWORD>(url.length()), 0, &components)) {
        wprintf((L"WinHttpCrackUrl(): " + ErrorMessage(GetLastError())).c_str());
    }

    std::wstring hostName(components.lpszHostName ? std::wstring{ components.lpszHostName, components.dwHostNameLength } : L"localhost");
    // Specify an HTTP server.
    if (hSession)
        hConnect = WinHttpConnect(hSession, hostName.c_str(),
                                  components.nPort, 0);

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"POST", components.lpszUrlPath,
            NULL, WINHTTP_NO_REFERER,
            WINHTTP_DEFAULT_ACCEPT_TYPES,
            0);

        std::wstring ContentType = L"Content-Type: multipart/form-data; boundary = UXht06QRx8JP1lr0IL67Uc";

        std::string prefileAppLogFile =
            "--UXht06QRx8JP1lr0IL67Uc\r\n"
            "Content-Disposition: form-data; name=\"DESKTOP-82L29F.ApplicationLog.UnknownCustomer\"\r\n"
            "\r\n";

        std::string prefileSystemLogFile =
            "--UXht06QRx8JP1lr0IL67Uc\r\n"
            "Content-Disposition: form-data; name=\"DESKTOP-82L29F.SystemLog.UnknownCustomer\"\r\n"
            "\r\n";

    std::string newLine = "\r\n";
    std::string finalBody = "\r\n--UXht06QRx8JP1lr0IL67Uc\r\n";

    bResults = WinHttpAddRequestHeaders(
        hRequest,
        ContentType.c_str(),
        -1L,
        WINHTTP_ADDREQ_FLAG_ADD
    );

    std::wstring contentLen = ContentLength(prefileAppLogFile.length() + applContents.length() + newLine.length() + prefileSystemLogFile.length() + systemContents.length() + finalBody.length());
    bResults = WinHttpSendRequest(hRequest, contentLen.c_str(), 0,
                WINHTTP_NO_REQUEST_DATA,
                0,
                WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH,
                NULL);

        DWORD dwBytesWritten = 0;
        if (bResults)
            bResults = WinHttpWriteData(hRequest, prefileAppLogFile.c_str(),
                prefileAppLogFile.length(),
                &dwBytesWritten);

        if (bResults)
            bResults = WinHttpWriteData(hRequest, applContents.c_str(),
                applContents.length(),
                &dwBytesWritten);

        if (bResults)
            bResults = WinHttpWriteData(hRequest, newLine.c_str(),
                newLine.length(),
                &dwBytesWritten);

        if (bResults)
            bResults = WinHttpWriteData(hRequest, prefileSystemLogFile.c_str(),
                prefileSystemLogFile.length(),
                &dwBytesWritten);

        bResults = WinHttpWriteData(hRequest, systemContents.c_str(),
                                    systemContents.length(),
                                    &dwBytesWritten);

        bResults = WinHttpWriteData(hRequest, finalBody.c_str(),
                    finalBody.length(),
                    &dwBytesWritten);

    // End the request.
    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    if (bResults)
    {
        DWORD status{}, len = sizeof(status);
        bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &len, NULL);
        printf("Status code = %d.\n", status);
    }
    else
    {
        wprintf(L"WinHttpReceiveResponse(): %s\n", ErrorMessage(GetLastError()).c_str());
    }

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);
}
© www.soinside.com 2019 - 2024. All rights reserved.