oss-upload-aws.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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('../package.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. debugger
  45. fs.readdir(dir, (err, files) => {
  46. if (err) {
  47. throw err
  48. }
  49. files.forEach(async file => {
  50. let filepath = path.join(dir, file)
  51. const state = fs.statSync(filepath)
  52. if (state.isDirectory()) {
  53. list_files(filepath, callback)
  54. } else {
  55. if (filepath.endsWith('.map') == false) {
  56. callback(filepath)
  57. }
  58. }
  59. })
  60. })
  61. }
  62. function uploads() {
  63. ;[
  64. {
  65. dir: '../../../dist/editor/editor',
  66. key: 'v4/cdfg/editor',
  67. },
  68. ].forEach(item => {
  69. list_files(toPath(path.join(__dirname, item.dir)), filepath => {
  70. let temppath = filepath.replace(/\\/g, '/')
  71. let keyspath = item.key + temppath.split(item.dir.replace(/\.\.\//g, ''))[1]
  72. if (item.sdk) {
  73. keyspath = item.key + '/' + package.version + temppath.split(item.dir)[1]
  74. }
  75. upload(filepath, keyspath, 'max-age=3153600') // 缓存30天
  76. })
  77. })
  78. }
  79. uploads()