ue4/ue5 Http上传文件
http请求报文
根据网页请求模板在UE4里面进行对应设置。下面代码可以作为一个标准上传格式
void Test::TestHttpFileUpload(FString FilePath)
{
TSharedRef<IHttpRequest, ESPMode::ThreadSafe> HttpRequest = FHttpModule::Get().CreateRequest();
//Host
FString Host = "http://192.168.60.83:10013";
//请求地址
FString URL = TEXT("/cdszls/file/uploadModFile");
HttpRequest->SetURL(FString(Host+URL));
FString Boundary = "UE4RuntimeEditor_" + FString::FromInt(FDateTime::Now().GetTicks());
//报文头
HttpRequest->SetHeader("Content-Type", "multipart/form-data; boundary=----" + Boundary);
//请求方法
HttpRequest->SetVerb(TEXT("POST"));
#pragma region 添加报文体
TArray<uint8> RequestContent;
TArray<uint8> FileContent;
if (FFileHelper::LoadFileToArray(FileContent, *FilePath))
{
FString FileName = FPaths::GetCleanFilename(FilePath);
//文件上传默认参数 name 是与后端约定的,一般叫file
TArray<uint8> FileHeaderArray = StringToByte("------" + Boundary + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + FileName + "\"\r\n" + "Content-Type: \r\n\r\n");
RequestContent.Append(FileHeaderArray);
RequestContent.Append(FileContent);
//其它参数 参数1 规则和上图的报文体一致 fileType 和folderName为后端需要的参数名,Texture为前端传入的值
FString PostVal1 = "\r\n------" + Boundary + "\r\nContent-Disposition: form-data; name=\"fileType\"\r\n\r\n" + "Texture";
RequestContent.Append(StringToByte(PostVal1));
//参数2
FString PostVal2 = "\r\n------" + Boundary + "\r\nContent-Disposition: form-data; name=\"folderName\"\r\n\r\n" + "Texture";
RequestContent.Append(StringToByte(PostVal2));
}
// 结束
FString EndBoundary = "\r\n------" + Boundary + "--\r\n";
RequestContent.Append(StringToByte(EndBoundary));
#pragma endregion
//设置大小
HttpRequest->SetHeader("Content-Length",FString::FromInt(RequestContent.Num()));
//设置请求体
HttpRequest->SetContent(RequestContent);
//发送请求
HttpRequest->ProcessRequest();
}
StringToByte为FString转TArray
TArray<uint8> Test::StringToByte(FString data)
{
TArray<uint8> byteArray;
FTCHARToUTF8 Convert(*data);
byteArray.Append((uint8*)((ANSICHAR*)Convert.Get()), Convert.Length());
return byteArray;
}