类型 函数 库 network.* 返回值 用户数据 修订 版本 2024.3703 关键词 异步, http, https, get, post, 上传 另请参阅 network.request() network.cancel() network.download() networkRequest
此 API 是一个便捷方法,与异步 network.request() 非常相似,不同之处在于它始终尝试从您指定的本地文件上传请求。实际上,此方法只是调用 network.request(),将源 filename 和 baseDirectory 参数放入 params.body 表中,将 contentType 添加为 params.headers 请求标头值,并指定 "upload" 进度通知。
此函数返回一个句柄,可以将其传递给 network.cancel() 以取消请求。
您不能在 applicationSuspend 或 applicationExit 事件 期间执行网络上传。当您的应用程序挂起时,不会触发任何回调。您可以通过在挂起时将您希望发出的请求保存到文件来解决此问题。然后,在 applicationResume 事件 上,检查是否有保存的待处理上传,如果有,则执行它。
网络请求在失败时不会引发运行时错误,因此无需将它们包装在 Lua pcall() 语句中(错误会在发送到网络侦听器的事件中报告)。
在 Android 上,您必须将 INTERNET 权限添加到 build.settings 文件中。
settings =
{
android =
{
usesPermissions =
{
"android.permission.INTERNET",
},
},
}
network.upload( url, method, listener [, params], filename [, baseDirectory] [, contentType] )
字符串. HTTP 请求 URL。
字符串. HTTP 方法;对于文件上传,通常应为 "PUT" 或 "POST"。
侦听器. 在 HTTP 操作的各个阶段调用的侦听器函数。它会传递一个 networkRequest 事件。当 progress 为 true 时,此 API 提供 "upload" 进度,这意味着侦听器将接收 "began"、"progress" 和 "ended" 阶段的事件。如果未启用 progress 参数,则仅使用 "ended" 阶段事件调用侦听器。
表. 指定 HTTP 请求处理选项的表,包括自定义请求标头。支持以下键
headers — 使用字符串键指定标头值的表。timeout — 超时时间(以秒为单位)。默认为 30 秒。仅在 Mac/iOS 上可用。bodyType — 指示字符串请求正文是 "text" 还是 "binary" 的字符串。默认为 "text"。progress — 设置为 true 将启用进度事件。默认为 nil,表示只需要 "ended" 阶段事件。字符串. 要上传的文件的名称。
常量. 要上传的文件的目录。如果未提供,则默认为 system.DocumentsDirectory。
常量. 正在上传的文件的 Content-Type。虽然此参数是可选的,但 **必须** 通过此参数或 params.header 值提供 Content-Type。
-- The following code demonstrates an HTTP post, where the request body is text from a file.
-- This example demonstrates just one possible way to upload a file. Different web servers
-- and applications support different methods of file upload. For example, some REST services
-- support upload of a binary file in the body of a PUT request. Many web servers only allow
-- file uploads using multipart/form-encoded (text) request bodies in a POST request. If you
-- are going to attempt file upload, you must first understand the specific mechanism
-- supported by the specific web server or application that you will be working with,
-- then you must form your request data and choose your request method appropriately.
local function networkListener( event )
if ( event.isError ) then
print( "Network error: ", event.response )
elseif ( event.phase == "ended" ) then
print ( "Upload complete!" )
end
end
network.upload(
"http://127.0.0.1/restapi.php",
"POST",
networkListener,
"object.json",
system.DocumentsDirectory,
"application/json"
)