【UE】HTTP接口上传文件_文件作为入参

文章描述了如何在UnrealEngine(UE)中通过BlueprintFunctionLibrary蓝图函数库实现文件上传,包括使用From-data格式、设置请求头、处理边界和Content-Type,以及调用HttpModule进行HTTPPOST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求

假设需要在UE中发送下方接口传输文件

在这里插入图片描述

省流

使用From-data格式
在请求头Content-Type中加入间隔符Boundary
使用LoadFileToArray()读取文件,并加入分隔符、文件头等内容 转成字节 作为Content

在C++中发送请求

创建BlueprintFunctionLibrary蓝图函数库
对应Build.cs中加入Http模块

PrivateDependencyModuleNames.Add("Http");

增加函数

.h中

UFUNCTION(BlueprintCallable, Category = "Gdoog", meta = (WorldContext = "WorldContextObject"))
	//发送上传文件的请求
	static void UploadFileHttp();
	
UFUNCTION(BlueprintPure, Category = "Gdoog", meta = (WorldContext = "WorldContextObject"))
	//字符串转字节,支持中文
	static TArray<uint8> ConvertStringToBytes(const FString& Data);

.cpp中
函数前改为自己的函数库名
文件读取相关头文件
#include “HAL/PlatformFileManager.h”
#include “Misc/FileHelper.h”

http相关头文件
#include “HttpModule.h”

//字符串转字节,支持中文
TArray<uint8> UG_FileHelperForBpBPLibrary::ConvertStringToBytes(const FString& Data)
{
	TArray<uint8> ResBytes;
	FTCHARToUTF8 Converter(*Data);
	ResBytes.SetNum(Converter.Length());
	FMemory::Memcpy(ResBytes.GetData(), (uint8*)(ANSICHAR*)Converter.Get(), ResBytes.Num());
	return ResBytes;
}

//发送上传文件的请求
void UG_FileHelperForBpBPLibrary::UploadFileHttp()
{
	const FString FilePath = "E:\\XiTong\\Desktop\\测试文件.xls";//文件路径
	const FString FileName = FPaths::GetCleanFilename(FilePath);//文件名字
	const FString HttpUrl = "127.0.0.1:1024/upload";//请求链接
	const FString HttpVerb = "POST";//请求方式
	const FString KeyOfFile = "file";//请求中文件的key
	const FString TypeOfFile = "application/vnd.ms-excel";//文件类型对应的type
	TMap<FString,FString> OtherInfo={{"Key1","Value1"},{"Key2","Value2"}};//其他请求参数
	TArray<uint8> FileContentBytes;//文件内容
	FFileHelper::LoadFileToArray(FileContentBytes, *FilePath);

	//随便创建一个间隔符
	const FString BoundaryLabel = FString(TEXT("e543322540af456f9a3773049ca02529-")) + FString::FromInt(FMath::Rand());
	//每个参数的头部都需要增加的  间隔符
	const FString BoundaryBegin = FString(TEXT("--")) + BoundaryLabel + FString(TEXT("\r\n"));
	//结束时需要增加的   间隔符
	const FString BoundaryEnd = FString(TEXT("\r\n--")) + BoundaryLabel + FString(TEXT("--\r\n"));


	//处理请求内容
	TArray<uint8> ResContent;
	
	/*   文件内容前	例	\r\n
	 *					--e543322540af456f9a3773049ca02529-183\r\n
	 *					Content-Disposition: form-data; name="file"; filename="测试文件.xls"\r\n
	 *					Content-Type: application/vnd.ms-excel\r\n\r\n
	*/
	const FString BeginFileString =
		"\r\n"
		+ BoundaryBegin
		+ "Content-Disposition: form-data; name=\"" + KeyOfFile + "\"; filename=\"" + FileName + "\"\r\n"
		+ "Content-Type: " + TypeOfFile + "\r\n\r\n";

	//加入文件前内容
	ResContent.Append(ConvertStringToBytes(BeginFileString));
	//加入文件内容
	ResContent.Append(FileContentBytes);
	
	/*		加入其他参数   例	\r\n
	 *						--e543322540af456f9a3773049ca02529-183\r\n
	 *						Content-Disposition: form-data; name="Key1"\r\n\r\n
	 *						Value1
	 */
	for (TPair<FString, FString> Info : OtherInfo)
	{
		ResContent.Append(ConvertStringToBytes(
			"\r\n"
			+ BoundaryBegin
			+ "Content-Disposition: form-data; name=\""+ Info.Key+"\"\r\n\r\n"
			+ Info.Value));
	}

	//加入结尾分隔符
	ResContent.Append(ConvertStringToBytes(BoundaryEnd));

	//创建请求
	FHttpModule& HttpModule = FHttpModule::Get();
	TSharedRef<IHttpRequest, ESPMode::ThreadSafe> HttpRequest = HttpModule.CreateRequest();
	HttpRequest->SetURL(HttpUrl);
	HttpRequest->SetVerb(HttpVerb);
	//替换请求头中的type,加入间隔符
	HttpRequest->SetHeader(TEXT("Content-Type"), FString(TEXT("multipart/form-data; boundary=")) + BoundaryLabel);
	//请求内容
	HttpRequest->SetContent(ResContent);

	//请求回调,按需处理
	// HttpRequest->OnProcessRequestComplete().BindLambda([this](UE_LOG(LogTemp, Error, TEXT("Connection.")););

	//发送
	HttpRequest->ProcessRequest();
}

其中
const FString TypeOfFile = “application/vnd.ms-excel”;//文件类型对应的type
可以对照这个表去设置
常见 content-type对应表https://blog.csdn.net/xiaoyu19910321/article/details/79279364

函数的变量可以 按需 暴露给蓝图
在这里插入图片描述

把入参转为字节配合其他节点

如果有使用插件的节点来请求http,比如这里使用的HttpLibrary插件,只需要构建Content,然后在请求头中的Content_Type加入分隔符即可
在这里插入图片描述
构建过程与上文相同,多了一步返回分隔符的步骤

UFUNCTION(BlueprintCallable, Category = "Gdoog|File|Http", meta = (DisplayName = "LoadFileToParameter", AutoCreateRefTerm="OtherInfo"))
	//将文件转化为入参,返回分隔符
	static bool LoadFileToParameter_G(const FString FileKey, const FString FilePath, const FString FileType, const TMap<FString, FString>& OtherInfo,TArray<uint8>& Result,FString& Boundary);
//将文件转化为入参
bool UG_FileHelperForBpBPLibrary::LoadFileToParameter_G(const FString FileKey, const FString FilePath, const FString FileType, const TMap<FString, FString>& OtherInfo,TArray<uint8>& Result,FString& Boundary)
{
	//Preprocess some values    Return Boundary
	Boundary = FString(TEXT("e543322540af456f9a3773049ca02529-")) + FString::FromInt(FMath::Rand());
	const FString BoundaryBegin = FString(TEXT("--")) + Boundary + FString(TEXT("\r\n"));
	const FString BoundaryEnd = FString(TEXT("\r\n--")) + Boundary + FString(TEXT("--\r\n"));
	TArray<uint8> FileBytes;
	FFileHelper::LoadFileToArray(FileBytes, *FilePath);


	//Build content
	Result.Append(ConvertStringToBytes(
		"\r\n"
		+ BoundaryBegin
		+ "Content-Disposition: form-data; name=\"" + FileKey + "\"; filename=\"" + FilePath + "\"\r\n"
		+ "Content-Type: " + FileType + "\r\n\r\n"));
	Result.Append(FileBytes);
	for (TPair<FString, FString> Info : OtherInfo)
	{
		Result.Append(ConvertStringToBytes(
			"\r\n"
			+ BoundaryBegin
			+ "Content-Disposition: form-data; name=\"" + Info.Key + "\"\r\n\r\n"
			+ Info.Value));
	}
	Result.Append(ConvertStringToBytes_G(BoundaryEnd));

	return true;
}

最后效果
在这里插入图片描述
需要额外注意使用的插件能否替换请求头中的Content_Type
作者使用的插件 在选择FromData之后是无法替换Content-Type的
在这里插入图片描述
修改判断条件 使其允许修改
在这里插入图片描述

参考链接

Upload an image using HTTP POST request C++
UE4如何上传文件
ue4/ue5 Http上传文件
常见 content-type对应表

<think>嗯,用户想了解如何在UE5中使用Varest插件实现文件上传功能。首先,我需要回忆一下Varest插件的基本用法。Varest插件在UE4/5中常用于处理HTTP请求和REST API交互,我之前在UE4的项目中用过它来连接后端服务。用户提到的文件上传,通常涉及到POST请求和multipart/form-data格式,这可能需要设置请求头和内容体。 接下来,我得确认Varest插件是否支持文件上传。根据之前的经验,Varest的UVaRestRequestJSON对象可以设置自定义的请求头和内容,但处理文件上传可能需要构造特定的表单数据。可能需要将文件内容转换为字节数组,并正确设置Content-Type为multipart/form-data,同时包含boundary分隔符。 然后,用户可能需要指导如何读取本地文件。在UE5中,可以使用FFileHelper类来读取文件到字节数组。比如,使用FFileHelper::LoadFileToArray方法。同时,需要注意文件的路径问题,可能需要将文件放在项目的Content目录下,或者处理沙盒路径的问题。 另外,服务器端的接收部分也需要考虑。用户可能需要一个能够处理文件上传的Web API,比如使用Node.js或PHP编写的接口。这部分可能需要引用已有的教程,比如用户提供的引用[1]中的UE4登录系统教程,可能涉及到Web API的设置,虽然具体文件上传的部分可能需要扩展。 还有,用户可能遇到的常见问题,比如请求头设置不正确、文件路径错误、服务器端无法解析上传的数据等。需要提醒用户检查这些点,并提供调试方法,比如打印响应内容或使用日志工具。 最后,生成相关问题时要考虑用户可能的后续需求,比如文件下载、进度显示、安全验证等,这些都是在实现文件上传后可能需要的功能扩展。</think>### UE5使用Varest插件实现文件上传功能 #### 一、环境配置准备 1. 安装Varest插件 - 通过Epic商城下载VaRest插件 - 在项目设置的Plugins中启用`VaRest Plugin` - 重启Unreal Editor完成加载 2. 创建Web API接口 - 建议使用Node.js Express搭建文件接收服务 ```javascript const express = require('express'); const fileUpload = require('express-fileupload'); const app = express(); app.use(fileUpload()); app.post('/upload', (req, res) => { if (!req.files) return res.status(400).send('No files uploaded'); const file = req.files.file; file.mv(__dirname + '/uploads/' + file.name); res.send('File uploaded!'); }); ``` - 该服务支持接收multipart/form-data格式请求[^1] #### 二、客户端实现步骤 1. 创建上传蓝图 ```python # 伪代码表示蓝图逻辑 Begin Object Class=/Script/BlueprintGraph.K2Node_CustomEvent Name="UploadFile" End Object Create VaRest Request Node -> Set Request Verb(POST) -> Set Request URL("http://your-api/upload") -> Construct Form Data -> Execute Request ``` 2. 文件处理关键代码 - 使用`FFileHelper`读取本地文件 ```cpp TArray<uint8> FileData; FString FilePath = FPaths::ProjectContentDir() / TEXT("Uploads/test.jpg"); FFileHelper::LoadFileToArray(FileData, *FilePath); ``` 3. 请求数配置 ```cpp UVaRestRequestJSON* Request = UVaRestRequestJSON::ConstructRequest(this); Request->SetVerb(EVaRestRequestVerb::POST); Request->SetContentType(EVaRestRequestContentType::x_www_form_urlencoded); // 添加文件字段 FVaRestFileParameter FileParam; FileParam.FileName = "test.jpg"; FileParam.Content = FileData; Request->AddFileParameter("file", FileParam); ``` #### 三、调试与验证 1. 使用Postman测试API接口 - 确认服务端能正常接收文件 2. 在蓝图中添加响应处理 ```python OnRequestComplete -> Branch(Response Code 200) -> Print String "Upload Success" ELSE Print String "Error: " + Response Content ``` 3. 查看输出日志确认传输状态 #### 四、常见问题解决 1. 403 Forbidden错误 - 检查CORS配置 - 添加请求头`Access-Control-Allow-Origin: *` 2. 文件损坏问题 - 验证Content-Type设置为`multipart/form-data` - 检查二进制传输模式 3. 路径问题 - 使用`FPaths`类处理跨平台路径
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值