oss-upload-test.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * @Author: Rindy
  3. * @Date: 2020-03-13 10:56:21
  4. * @LastEditors: Rindy
  5. * @LastEditTime: 2021-09-16 10:20:55
  6. * @Description: 静态文件上传
  7. */
  8. const fs = require('fs')
  9. const url = require('url')
  10. const path = require('path')
  11. const OSS = require('ali-oss')
  12. const package = require('../lerna.json')
  13. let client = new OSS({
  14. region: 'oss-cn-shenzhen',
  15. accessKeyId: 'LTAI4FreM2331vLtfDfG7qfX',
  16. accessKeySecret: 's8g77lxt1KPxCzDE4hyjwlAgPwfhnG',
  17. bucket: '4dkankan',
  18. timeout: 120000,
  19. maxSockets: 200,
  20. })
  21. const toPath = dist => path.resolve(dist)
  22. async function upload(filepath, key, cache, retry = 0) {
  23. try {
  24. let result = await client.put(key, filepath, {
  25. headers: {
  26. 'Cache-Control': cache,
  27. },
  28. })
  29. if (result.res.status != 200) {
  30. console.log('上传失败:' + key, 'status code:' + result.res.status)
  31. } else {
  32. console.log('上传成功:' + key)
  33. }
  34. } catch (err) {
  35. if (++retry < 3) {
  36. return upload(filepath, key, cache, retry)
  37. }
  38. console.log('上传失败:' + key)
  39. throw err
  40. }
  41. }
  42. function list_files(dir, callback) {
  43. fs.readdir(dir, (err, files) => {
  44. if (err) {
  45. throw err
  46. }
  47. files.forEach(async file => {
  48. let filepath = path.join(dir, file)
  49. const state = fs.statSync(filepath)
  50. if (state.isDirectory()) {
  51. list_files(filepath, callback)
  52. } else {
  53. if (filepath.endsWith('.map') == false) {
  54. callback(filepath)
  55. }
  56. }
  57. })
  58. })
  59. }
  60. function uploads() {
  61. ;[
  62. {
  63. dir: 'dist/editor/editor',
  64. key: 'v4-test/www/editor',
  65. },
  66. {
  67. dir: 'dist/viewer/viewer',
  68. key: 'v4-test/www/viewer',
  69. },
  70. {
  71. dir: 'dist/sdk',
  72. key: 'v4-test/www/sdk',
  73. },
  74. {
  75. dir: 'dist/sdk',
  76. key: 'v4-test/sdk',
  77. sdk: true,
  78. },
  79. ].forEach(item => {
  80. list_files(toPath(item.dir), filepath => {
  81. let temppath = filepath.replace(/\\/g, '/')
  82. let keyspath = item.key + temppath.split(item.dir)[1]
  83. if (item.sdk) {
  84. keyspath = item.key + '/' + package.version + temppath.split(item.dir)[1]
  85. }
  86. upload(filepath, keyspath, 'max-age=3153600') // 缓存30天
  87. })
  88. })
  89. }
  90. uploads()