Files
daydaytalk-fwutils/target/tencent/cos.lua
2026-01-08 21:58:41 +08:00

150 lines
3.2 KiB
Lua

local tencent_cos = require("tencent_cos")
local fw = require("fastweb")
local utils = require("app.utils")
local config = require("app.config")
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"
}
}
function M.upload_data(config,object_name,remote_dir,data,ext)
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 = tencent_cos.new()
local local_file = fw.website_dir()..config.path.temp.."/"..filename
utils.save_file(local_file,data)
local cos_filepath = remote_dir..dirpath.."/"..filename
local result = cos:upfile(
config.appid,
config.endpoint,
config.secret_id,
config.secret_key,
object_name,
cos_filepath,
local_file
)
if result == "" then
return true,cos_filepath
end
return false,result
end
function M.upload_file(config,object_name,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 cos = tencent_cos.new()
local result = cos:upfile(
config.appid,
config.endpoint,
config.secret_id,
config.secret_key,
object_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
return M