oss.lua 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. local aliyun_oss = require("aliyunoss")
  2. local fw = require("fastweb")
  3. local utils = require("utils")
  4. local M = {}
  5. -- 文件扩展名与目录的映射
  6. M.ext_dirpath = {
  7. images = {
  8. "jpg",
  9. "jpeg",
  10. "png",
  11. "gif",
  12. "bmp",
  13. "webp",
  14. "svg",
  15. "ico",
  16. "tif",
  17. "tiff",
  18. },
  19. videos = {
  20. "mp4",
  21. "avi",
  22. "mov",
  23. "wmv",
  24. "flv"
  25. },
  26. audio = {
  27. "mp3",
  28. "wav",
  29. "ogg",
  30. "aac",
  31. "m4a",
  32. "wma"
  33. },
  34. documents = {
  35. "pdf",
  36. "doc",
  37. "docx",
  38. "xls",
  39. "xlsx",
  40. "ppt",
  41. "pptx"
  42. }
  43. }
  44. function M.upload_file(config,remote_dir,local_filepath,auto_remove)
  45. if not utils.exists_file(local_filepath) then
  46. return false,"文件不存在,local_filepath: "..local_filepath
  47. end
  48. local ext = utils.ext(local_filepath)
  49. local filename = fw.make_software_guid().."."..ext
  50. local dirpath = ""
  51. for dir, ext_list in pairs(M.ext_dirpath) do
  52. for _, ext_type_ext in ipairs(ext_list) do
  53. if ext_type_ext == ext then
  54. dirpath = dir
  55. break
  56. end
  57. end
  58. if dirpath ~= "" then
  59. break
  60. end
  61. end
  62. if dirpath == "" then
  63. return false,"不支持的文件格式,ext: "..ext
  64. end
  65. if remote_dir == nil or remote_dir == "" then
  66. remote_dir = ""
  67. else
  68. remote_dir = remote_dir.."/"
  69. end
  70. local cos_filepath = remote_dir .. dirpath.."/"..filename
  71. local oss = aliyun_oss.new()
  72. local result = oss:upfile(
  73. config.endpoint,
  74. config.access_key_id,
  75. config.access_key_secret,
  76. config.bucket_name,
  77. cos_filepath,
  78. local_filepath,
  79. ""
  80. )
  81. if result == "" then
  82. if auto_remove then
  83. utils.delete_file(local_filepath)
  84. end
  85. return true,cos_filepath
  86. end
  87. return false,result
  88. end
  89. return M