ue4/ue5 Http上传文件

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 + "rnContent-Disposition: form-data; name="file"; filename="" + FileName + ""rn" + "Content-Type: rnrn");
		RequestContent.Append(FileHeaderArray);
		RequestContent.Append(FileContent);

		//其它参数 参数1 规则和上图的报文体一致 fileType 和folderName为后端需要的参数名,Texture为前端传入的值

		FString PostVal1 = "rn------" + Boundary + "rnContent-Disposition: form-data; name="fileType"rnrn" + "Texture";
		RequestContent.Append(StringToByte(PostVal1));
		//参数2
		FString PostVal2 = "rn------" + Boundary + "rnContent-Disposition: form-data; name="folderName"rnrn" + "Texture";
		RequestContent.Append(StringToByte(PostVal2));
		
	}

	// 结束
	FString EndBoundary = "rn------" + Boundary + "--rn";
	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;
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>