赞
踩
上传文件示例代码
- /*
- InUrl为上传URL
- InFiles为本地文件路径的数组
- Boundary为分隔符,用来分隔文件,其他地方不能出现该字符串,每个文件都以"\r\n--"+Boundary+"\r\n"开始(即BeginBoundry)
- 分隔符之后是文件头(FileHeader),文件头中name为文件域,这里用"file[]",[]表示上传多个文件,如果是一个文件可去掉[];filename为文件名,这里用本地文件名;文件头以两个换行符(\r\n\r\n)结束
- 文件头之后紧跟文件内容
- 所有文件内容都读出之后,最后以"\r\n--"+Boundary+"--\r\n"结束
- */
- bool UploadFiles(const FString& InUrl,const TArray<FString>& InFiles)
- {
- TSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();
- HttpRequest->SetURL(InUrl);
-
- FString Boundary = "---------------------------" + FString::FromInt(FDateTime::Now().GetTicks());//分隔符
- HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("multipart/form-data; boundary =" + Boundary));//请求头,数据格式必须是multipart/form-data
- HttpRequest->SetVerb(TEXT("POST"));
-
- TArray<uint8> UploadContent;
- for (const FString& FilePath : InFiles)
- {
- TArray<uint8> ArrayContent;
- if (FFileHelper::LoadFileToArray(ArrayContent, *FilePath))
- {
- FString BeginBoundry = "\r\n--" + Boundary + "\r\n";
- UploadContent.Append((uint8*)TCHAR_TO_ANSI(*BeginBoundry), BeginBoundry.Len());
-
- FString FileHeader = "Content-Disposition: form-data;";//文件头
- FileHeader.Append("name=\"file[]\";");
- FileHeader.Append("filename=\"" + FPaths::GetCleanFilename(FilePath) + "\"");
- FileHeader.Append("\r\nContent-Type: \r\n\r\n");
- UploadContent.Append((uint8*)TCHAR_TO_ANSI(*FileHeader), FileHeader.Len());
-
- UploadContent.Append(ArrayContent);
- }
- }
- FString EndBoundary = "\r\n--" + Boundary + "--\r\n";//结束符
- UploadContent.Append((uint8*)TCHAR_TO_ANSI(*EndBoundary), EndBoundary.Len());
- HttpRequest->SetContent(UploadContent);
- return HttpRequest->ProcessRequest();
- }
最终的上传内容类似于以下格式:
------------------------------1498579920
Content-Disposition: form-data;name="files[]";filename="A1.png"
Content-Type:
{文件内容}
------------------------------1498579920
Content-Disposition: form-data;name="files[]";filename="A2.png"
Content-Type:
{文件内容}
------------------------------1498579920
Content-Disposition: form-data;name="files[]";filename="A3.png"
Content-Type:
{文件内容}
------------------------------1498579920--
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。