oss-upload-aws.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * @Author: Rindy
  3. * @Date: 2020-03-13 10:56:21
  4. * @LastEditors: Rindy
  5. * @LastEditTime: 2022-05-26 10:20:55
  6. * @Description: 静态文件上传
  7. */
  8. const { S3 } = require('@aws-sdk/client-s3')
  9. const fs = require('fs')
  10. const path = require('path')
  11. const mime = require('mime')
  12. const package = require('../lerna.json')
  13. process.env.AWS_ACCESS_KEY_ID = 'AKIAWCV5QFZ34YYVET2Q'
  14. process.env.AWS_SECRET_ACCESS_KEY = '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'
  15. const client = new S3({ region: 'eu-west-2' })
  16. const toPath = dist => path.resolve(dist)
  17. async function upload(filepath, key, cache, retry = 0) {
  18. fs.readFile(filepath, (err, fileData) => {
  19. if (err) {
  20. console.log('上传失败:' + filepath)
  21. throw err
  22. }
  23. client.putObject(
  24. {
  25. Bucket: '4dkankan',
  26. Key: key,
  27. Body: fileData,
  28. ContentType: mime.getType(filepath),
  29. },
  30. (err, data) => {
  31. if (err) {
  32. if (++retry < 3) {
  33. return upload(filepath, key, cache, retry)
  34. }
  35. console.log('上传失败:' + filepath)
  36. throw err
  37. }
  38. console.log('上传成功:' + key)
  39. }
  40. )
  41. })
  42. }
  43. function list_files(dir, callback) {
  44. fs.readdir(dir, (err, files) => {
  45. if (err) {
  46. throw err
  47. }
  48. files.forEach(async file => {
  49. let filepath = path.join(dir, file)
  50. const state = fs.statSync(filepath)
  51. if (state.isDirectory()) {
  52. list_files(filepath, callback)
  53. } else {
  54. if (filepath.endsWith('.map') == false) {
  55. callback(filepath)
  56. }
  57. }
  58. })
  59. })
  60. }
  61. function uploads() {
  62. ;[
  63. {
  64. dir: 'dist/editor/editor',
  65. key: 'v4/www/editor',
  66. },
  67. {
  68. dir: 'dist/viewer/viewer',
  69. key: 'v4/www/viewer',
  70. },
  71. {
  72. dir: 'dist/sdk',
  73. key: 'v4/www/sdk',
  74. },
  75. {
  76. dir: 'dist/sdk',
  77. key: 'v4/sdk',
  78. sdk: true,
  79. },
  80. ].forEach(item => {
  81. list_files(toPath(item.dir), filepath => {
  82. let temppath = filepath.replace(/\\/g, '/')
  83. let keyspath = item.key + temppath.split(item.dir)[1]
  84. if (item.sdk) {
  85. keyspath = item.key + '/' + package.version + temppath.split(item.dir)[1]
  86. }
  87. upload(filepath, keyspath, 'max-age=3153600') // 缓存30天
  88. })
  89. })
  90. }
  91. uploads()