UE4上传图片到服务器

时间:2024-06-18 13:03:38

客户端代码:

void AHttpTestCharacter::MyHttpCall(FString Url)
{
// TexturePath contains the local file full path
FString TexturePath = TEXT("H:/SVN/VRHome/Saved/Screenshots/Windows/0.jpg");
// file name
int32 LastSlashPos;
TexturePath.FindLastChar('/', LastSlashPos);
FString FileName = TexturePath.RightChop(LastSlashPos + 1);

// get data
TArray<uint8> UpFileRawData;
FFileHelper::LoadFileToArray(UpFileRawData, *TexturePath);

FString JsonStr;
TSharedRef< TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR> > > JsonWriter = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR> >::Create(&JsonStr);
JsonWriter->WriteObjectStart();
JsonWriter->WriteValue(TEXT("FileToUpload"), TEXT("FileName"));
JsonWriter->WriteValue(TEXT("ImageData"), FBase64::Encode(UpFileRawData));
JsonWriter->WriteObjectEnd();
// Close the writer and finalize the output such that JsonStr has what we want
JsonWriter->Close();

TSharedRef<IHttpRequest> Request = FHttpModule::Get().CreateRequest();

Request->SetHeader(TEXT("Content-Type"), TEXT("application/json;charset=utf-8"));
Request->SetURL(TEXT("http://localhost/1.php"));
Request->SetVerb(TEXT("POST"));
Request->SetContentAsString(JsonStr);
Request->ProcessRequest();
Request->OnProcessRequestComplete().BindUObject(this, &AHttpTestCharacter::OnResponseReceived);
//GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, value);//prints nothing
}

服务器是PHP的,代码如下:

<?php

// 首先接收上传的数据

$post_data = file_get_contents('php://input');

// 解析json字符串

$obj = json_decode($post_data);

// 获取包含在Json字符串中的数据

// echo $obj->{'ImageData'};

$myfile=fopen("newfile.png", "w") or die("Unable to open file!");

$txt = base64_decode($obj->{'ImageData'});

fwrite($myfile,$txt);

echo "成功啦!";
?>