我有一个将文件上传到服务器的代码。出于测试目的,我使用 Apache 在我的 PC 上创建了一个本地服务器(localhost)。我的程序正在制作/上传与原始文件同名的文件,但其内容已被复制。在我的程序中,我使用“文件内容在这里”这一行进行调试,它是写入上传文件的唯一行。我使用了一个 PHP 脚本,它将接受文件并将其上传到指定位置。现在我很困惑这是PHP的问题还是它是否在我的代码中。这是我的代码片段:-
static TCHAR frmdata[] = "-----------------------------7d82751e2bc0858\r\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"D:\\er.txt\"\r\nContent-Type: text/plain\r\n\r\nfile contents here\r\n-----------------------------7d82751e2bc0858--\r\n";
static TCHAR hdrs[] = "Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858";
HINTERNET hSession = InternetOpen("MyBrowser",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(!hSession)
{
cout<<"Error: InternetOpen";
}
HINTERNET hConnect = InternetConnect(hSession, _T("localhost"),INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if(!hConnect)
{
cout<<"Error: InternetConnect";
}
//HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",_T("upload.php"), NULL, NULL, (const char**)"*/*\0", 0, 1);
LPCTSTR rgpszAcceptTypes[] = {_T("*/*"), NULL};
HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",
_T("upload.php"), NULL, NULL,
rgpszAcceptTypes, 0, 1);
if(hRequest==NULL)
{
cout<<"Error: HttpOpenRequest";
}
BOOL sent= HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
if(!sent)
{
cout<<"Error: HttpSendRequest "<<GetLastError();
}
char buffer[2048] = {};
DWORD bufferSize = sizeof(buffer);
BOOL success = HttpQueryInfo(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, buffer, &bufferSize, NULL);
if(!success)
{
std::cout<<"Error: HttpQueryInfo "<< GetLastError();
return 0;
}
std::cout << buffer << std::endl;
ZeroMemory(buffer, sizeof(buffer));
success = InternetReadFile(hRequest, buffer, sizeof(buffer), &bufferSize);
if(!success)
{
std::cout << "Error: InternetReadFile " << GetLastError();
return 0;
}
std::cout << buffer << std::endl;
//close any valid internet-handles
InternetCloseHandle(hSession);
InternetCloseHandle(hConnect);
InternetCloseHandle(hRequest);
getchar();
这是 PHP 脚本:-
if (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
echo "File ". $_FILES['uploadedfile']['name'] ." uploaded successfully. ";
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully moved. ";
}
else
print_r($_FILES);
}
else {
echo "Upload Failed!!!";
print_r($_FILES);
}