Files
2026-02-21 19:26:14 +08:00

153 lines
3.1 KiB
Lua

local aliyun_oss = require("aliyunoss")
local fw = require("fastweb")
local utils = require("utils")
local M = {}
-- 文件扩展名与目录的映射
M.ext_dirpath = {
images = {
"jpg",
"jpeg",
"png",
"gif",
"bmp",
"webp",
"svg",
"ico",
"tif",
"tiff",
},
videos = {
"mp4",
"avi",
"mov",
"wmv",
"flv"
},
audio = {
"mp3",
"wav",
"ogg",
"aac",
"m4a",
"wma"
},
documents = {
"pdf",
"doc",
"docx",
"xls",
"xlsx",
"ppt",
"pptx",
"txt",
"json",
"xml",
"html",
"css",
"js",
}
}
function M.upload_file(config,remote_dir,local_filepath,auto_remove)
if not utils.exists_file(local_filepath) then
return false,"文件不存在,local_filepath: "..local_filepath
end
local ext = utils.ext(local_filepath)
local filename = fw.make_software_guid().."."..ext
local dirpath = ""
for dir, ext_list in pairs(M.ext_dirpath) do
for _, ext_type_ext in ipairs(ext_list) do
if ext_type_ext == ext then
dirpath = dir
break
end
end
if dirpath ~= "" then
break
end
end
if dirpath == "" then
return false,"不支持的文件格式,ext: "..ext
end
if remote_dir == nil or remote_dir == "" then
remote_dir = ""
else
remote_dir = remote_dir.."/"
end
local cos_filepath = remote_dir .. dirpath.."/"..filename
local oss = aliyun_oss.new()
local result = oss:upfile(
config.endpoint,
config.access_key_id,
config.access_key_secret,
config.bucket_name,
cos_filepath,
local_filepath,
""
)
if result == "" then
if auto_remove then
utils.delete_file(local_filepath)
end
return true,cos_filepath
end
return false,result
end
function M.upload_data(config,remote_dir,data,ext)
if #data == 0 then
return false,"数据为空"
end
local filename = fw.make_software_guid().."."..ext
local dirpath = ""
for dir, ext_list in pairs(M.ext_dirpath) do
for _, ext_type_ext in ipairs(ext_list) do
if ext_type_ext == ext then
dirpath = dir
break
end
end
if dirpath ~= "" then
break
end
end
if dirpath == "" then
return false,"不支持的文件格式,ext: "..ext
end
if remote_dir == nil or remote_dir == "" then
remote_dir = ""
else
remote_dir = remote_dir.."/"
end
local cos_filepath = remote_dir .. dirpath.."/"..filename
local oss = aliyun_oss.new()
local result = oss:updata(
config.endpoint,
config.access_key_id,
config.access_key_secret,
config.bucket_name,
cos_filepath,
data
)
if result == "" then
return true,cos_filepath
end
return false,result
end
return M