帮我用andlua写一个指定目录下的所有txtzip文件上传到服务器
下面是一个使用AndLua在Android设备上将指定目录下的所有txt和zip文件上传到服务器的例子:
local http = require("socket.http")
local ltn12 = require("ltn12")
local lfs = require("lfs")
local uploadUrl = "http://your.server.com/upload.php"
local directoryPath = "/sdcard/your/directory/path/"
function uploadFiles()
for file in lfs.dir(directoryPath) do
if file ~= "." and file ~= ".." then
local filePath = directoryPath .. file
if file:match("%.txt$") or file:match("%.zip$") then
local fileContents = readFileContents(filePath)
if fileContents then
local request = createHttpRequest(filePath, fileContents)
local response = {}
local _, statusCode = http.request{
url = uploadUrl,
method = "POST",
headers = request.headers,
source = ltn12.source.string(request.body),
sink = ltn12.sink.table(response)
}
if statusCode == 200 then
print("Successfully uploaded file: " .. filePath)
else
print("Failed to upload file: " .. filePath)
end
end
end
end
end
end
function readFileContents(filePath)
local file = io.open(filePath, "rb")
if file then
local contents = file:read("*all")
file:close()
return contents
end
return nil
end
function createHttpRequest(filePath, fileContents)
local body = "file=" .. fileContents
local headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
["Content-Length"] = tostring(#body)
}
return { body = body, headers = headers }
end
uploadFiles()
请确保在设备上已经安装了AndLua,并将上述代码保存到一个名为upload.lua的文件中。然后在AndLua中执行该脚本,它将在指定的目录下查找所有的txt和zip文件,并将它们上传到指定的服务器URL。
您需要将uploadUrl变量设置为您实际的上传URL,将directoryPath变量设置为您想要上传文件的目录路径。确保您的服务器端有一个处理文件上传的脚本(在上面的例子中为upload.php),可以接收POST请求并将文件内容保存到适当的位置。
请注意,上述代码只是一个初步的示例,您可能需要根据您的实际需求进行调整和改进
原文地址: http://www.cveoy.top/t/topic/iX3v 著作权归作者所有。请勿转载和采集!