UE客户端封装http图片文件上传

核心代码
主要封装form表单对本地文件目录地址进行图片上传

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=“file”; filename=“截屏2022-09-23 18.39.33.png”
Content-Type:

(data)
----WebKitFormBoundary7MA4YWxkTrZu0gW

TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
	HttpRequest->SetURL(InUrl);

	// Request header
	FString Boundary = "---------------------------" + FString::FromInt(FDateTime::Now().GetTicks());
	HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("multipart/form-data; boundary =" + Boundary));
	HttpRequest->SetVerb(TEXT("POST"));

	//The bit array format of the request's content
	TArray<uint8> RequestContent;	

	// The bit array format of a single file
	TArray<uint8> FileContent;
	if (FFileHelper::LoadFileToArray(FileContent, *FilePath))
	{
		// Begin Boundry
		FString BeginBoundry = "\r\n--" + Boundary + "\r\n";
		RequestContent.Append((uint8*)TCHAR_TO_ANSI(*BeginBoundry), BeginBoundry.Len());

		// File Header
		FString FileHeader = "Content-Disposition: form-data;name=\"myFile\";";
		FileHeader.Append("filename=\"" + FPaths::GetCleanFilename(FilePath) + "\"\r\n");
		FileHeader.Append("Content-Type: \r\n\r\n");
		RequestContent.Append((uint8*)TCHAR_TO_ANSI(*FileHeader), FileHeader.Len());

		// File Content
		RequestContent.Append(FileContent);		
	}

	// End Boundry
	FString EndBoundary = "\r\n--" + Boundary + "--\r\n";
	RequestContent.Append((uint8*)TCHAR_TO_ANSI(*EndBoundary), EndBoundary.Len());

	HttpRequest->SetContent(RequestContent);
	HttpRequest->OnProcessRequestComplete().BindUObject(this, &AHttpService::UploadResponse);
	return HttpRequest->ProcessRequest();

你可能感兴趣的:(技术积累,http,前端,网络协议)