[英]Winhttp Does Not Post File
我在這里梳理了類似的問題並完成了所有建議,但由於某些奇怪的原因,我的代碼沒有將文件上傳到服務器。
C++代碼
#include <Windows.h>
#include <stdio.h>
#include <winhttp.h>
#include <shlwapi.h>
#pragma comment(lib, "Winhttp.lib")
#pragma comment(lib, "Shlwapi.lib")
PCHAR sendWebRequest(LPWSTR szServerNameOrIP, LPWSTR szVerb, LPWSTR szServerPath, PCHAR szFileToPost)
{
HINTERNET hSession;
HINTERNET hConnect;
HINTERNET hRequest;
BOOL bResults = FALSE;
LPCWSTR szUserAgent = L"MyCustomUserAgent";
DWORD dwSize, dwDownloaded;
PCHAR szTempRespBuff;
PCHAR szRawResponse = (PCHAR)malloc(MAX_PATH);
strcpy_s(szRawResponse, MAX_PATH, "");
int nBuffSize;
try{
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen(szUserAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (hSession == NULL)
{
//printf("[x] Could not create session!\n");
MessageBox(0, L"WinOpenError", L"", 0);
throw(0);
}
// Specify an HTTP server.
hConnect = WinHttpConnect(hSession, szServerNameOrIP, INTERNET_DEFAULT_HTTP_PORT, 0);
if (hConnect == NULL)
{
//printf("[x] Could not connect to the host!\n");
MessageBox(0, L"WinConnectError", L"", 0);
throw(0);
}
// Create an HTTP request handle.
hRequest = WinHttpOpenRequest(hConnect, szVerb, szServerPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
if (hRequest == NULL)
{
//printf("[x] Failed to get request handle!\n");
MessageBox(0, L"WinOpenRequestError", L"", 0);
throw(0);
}
// Add request headers.
bResults = WinHttpAddRequestHeaders(hRequest,
L"Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryaUZw4AF9WYYzUrpM",
-1L, WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE);
if (!bResults)
{
MessageBox(0, L"WinHttpAddRequestHeadersError", L"", 0);
throw(0);
}
CHAR szPostData0[440],
szPostData1[60],
szPostTemp[120];
ZeroMemory(szPostData0, sizeof(szPostData0));
ZeroMemory(szPostData1, sizeof(szPostData1));
ZeroMemory(szPostTemp, sizeof(szPostTemp));
strcpy_s(szPostData0, 440, "------WebKitFormBoundaryaUZw4AF9WYYzUrpM\r\n");
PCHAR fileName = PathFindFileNameA(szFileToPost);
wsprintfA(szPostTemp, "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"%s\"\r\n", fileName);
strcat_s(szPostData0, 440, szPostTemp);
strcat_s(szPostData0, 440, "Content-Type: text/plain\r\n\r\n");
strcpy_s(szPostData1, 60, "\r\n------WebKitFormBoundarygQFYVyK9cnuuaQYb--\r\n");
// Open the existing file.
HANDLE hFile = CreateFileA(szFileToPost, GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
MessageBox(0, L"CreateFileAError", L"", 0);
throw(0);
}
//Make sure size is not more than 300kb
size_t fileSize = GetFileSize(hFile, NULL);
if (fileSize > 307200)
{
MessageBox(0, L"FileSize too large!", L"", 0);
throw(0);
}
//Send Request
int lenBytes = strlen(szPostData0 + 1) + strlen(szPostData1 + 1) + fileSize;
bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS , 0, WINHTTP_NO_REQUEST_DATA, 0, lenBytes, NULL);
if (!bResults)
{
//printf("[x] Failed to send request!\n");
int error = GetLastError();
TCHAR szbuff[25];
wsprintf(szbuff, L"Error %d", error);
MessageBox(0, L"WinSendRequestError", szbuff, 0);
throw(0);
}
//Write First Post Data
DWORD numberOfBytesRead, numberOfBytesWritten;
WinHttpWriteData(hRequest, szPostData0, (DWORD)strlen(szPostData0+1), &numberOfBytesWritten);
//Write File Buffer
PCHAR fileBytes = (PCHAR)malloc(fileSize);
ReadFile(hFile, fileBytes, fileSize, &numberOfBytesRead, NULL);
WinHttpWriteData(hRequest, fileBytes, fileSize, &numberOfBytesWritten);
//Write Last Post Data
WinHttpWriteData(hRequest, szPostData1, (DWORD)strlen(szPostData1+1), &numberOfBytesWritten);
//Receive the response
bResults = WinHttpReceiveResponse(hRequest, NULL);
if (!bResults)
{
int err = GetLastError();
wsprintfA(szPostTemp, "WinHttpReceiveResponseError %d", err);
MessageBoxA(0, szPostTemp, "", 0);
throw(0);
}
//Read Response Received
do {
// Check for available data.
dwSize = 0;
if( !WinHttpQueryDataAvailable(hRequest, &dwSize) )
{
//printf( "Error %u in WinHttpQueryDataAvailable.\n", GetLastError() );
MessageBox(0, L"WinHttpQueryDataAvailableError", L"", 0);
throw(0);
}
// Allocate space for the buffer.
nBuffSize = (dwSize+1);
szTempRespBuff = (PCHAR)malloc(nBuffSize);
if (szTempRespBuff == NULL)
{
//printf( "Error allocation space for response");
throw(0);
}
// Read the data.
ZeroMemory(szTempRespBuff, nBuffSize);
if(WinHttpReadData( hRequest, (LPVOID)szTempRespBuff, dwSize, &dwDownloaded ))
strcat_s(szRawResponse, MAX_PATH, szTempRespBuff);
// Free the memory allocated to the buffer.
free(szTempRespBuff);
}while (dwSize > 0);
//Close Handles
WinHttpCloseHandle(hSession);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hRequest);
return szRawResponse;
}catch(...)
{
if(hSession)
WinHttpCloseHandle(hSession);
if(hConnect)
WinHttpCloseHandle(hConnect);
if(hRequest)
WinHttpCloseHandle(hRequest);
}
return "WINHTTP_ERROR";
}
int main()
{
PCHAR response = sendWebRequest(L"127.0.0.1", L"POST", L"/panel/ups.php", "hello.txt");
MessageBoxA(0, response, "", 0);
return 0;
}
PHP 代碼
<?php
if(isset($_FILES['fileToUpload'])){
$errors= array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size =$_FILES['fileToUpload']['size'];
$file_tmp =$_FILES['fileToUpload']['tmp_name'];
$file_type=$_FILES['fileToUpload']['type'];
$file_ext = explode('.',$_FILES['fileToUpload']['name']);
$file_ext=strtolower(end($file_ext));
$extensions= array("jpeg","jpg","png", "txt");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file or Txt";
}
if($file_size > 1048576){
$errors[]='File size must not exceed 1 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="fileToUpload" />
<input type="submit"/>
</form>
</body>
</html>
我究竟做錯了什么? 我在服務器(php)上得到“成功”回顯,但沒有文件上傳到圖像目錄中。 我發現該文件沒有$_FILES['fileToUpload']['tmp_name']
並且$_FILES['fileToUpload']['size']
是 0 字節。
我終於解決了這個問題。 當我使用較短的邊界時,文件會被上傳。 當我使用更長的時間時,它不會。 在服務器端,我監聽了返回 3(部分文件上傳)的文件錯誤。 我不知道為什么會這樣,但我想我必須堅持使用較短的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.