文档

Unity Engine

Unity Engine

Unity Web Request Creating Upload Handlers

Send request body data to a server using the UploadHandlerRaw and UploadHandlerFile upload handlers.
阅读时间2 分钟最后更新于 1 个月前

目前有两种类型的上传处理程序可用:
UploadHandlerRaw
和
UploadHandlerFile
。
UploadHandlerRaw
类在构建时接受数据缓冲区。当此缓冲区为字节数组时,将在内部复制到原生代码内存中。当远程服务器准备好接收请求主体数据时,
UnityWebRequest
系统会使用此缓冲区。当缓冲区作为
NativeArray
提供时,不会执行复制。
UploadHandlerFile
允许您将文件的内容作为请求主体发送。使用此处理程序可以将大文件发送到服务器,而无需使用大量内存。当处理程序从文件读取数据然后发送数据时,在任何给定时间,只有一小部分文件保留在内存中。
上传处理程序还接受“Content Type”字符串。如果在 UnityWebRequest 自身中没有设置
Content-Type
标头,则此字符串用于 UnityWebRequest 的
Content-Type
标头值。如果在 UnityWebRequest 对象上手动设置了
Content-Type
标头,则将忽略上传处理程序对象上的
Content-Type
。
如果没有在 UnityWebRequest 或
UploadHandler
上设置
Content-Type
,则系统会将
Content-Type
默认设置为
application/octet-stream
。
UnityWebRequest
具有一个
disposeUploadHandlerOnDispose
属性,其默认值为 true。如果此属性为 true,则在处理 UnityWebRequest 对象时,还将在附加的上传处理程序上调用 Dispose(),致使上传处理程序无用。如果保持对上传处理程序的引用时间长度超过对 UnityWebRequest 的引用时间长度,应将 disposeUploadHandlerOnDispose 设置为 false。

示例

byte[] payload = new byte[1024];// ... fill payload with data ...UnityWebRequest wr = new UnityWebRequest("https://www.mysite.com/data-upload");UploadHandler uploader = new UploadHandlerRaw(payload);// Sends header: "Content-Type: custom/content-type";uploader.contentType = "custom/content-type";wr.uploadHandler = uploader;