展品维保小程序前端代码接口
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

159 lines
4.2 KiB

2 weeks ago
  1. import config from '@/config'
  2. import Crypto from '@/utils/oss-upload/common/crypto/crypto.js.js'
  3. import '@/utils/oss-upload/common/crypto/hmac.js'
  4. import '@/utils/oss-upload/common/crypto/sha1.js'
  5. import { Base64 } from '@/utils/oss-upload/common/crypto/base64.js'
  6. /**
  7. * 生成随机Key
  8. */
  9. function storeKey() {
  10. let s = [];
  11. let hexDigits = "0123456789abcdef";
  12. for (let i = 0; i < 36; i++) {
  13. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  14. }
  15. s[14] = "4";
  16. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  17. s[8] = s[13] = s[18] = s[23] = "-";
  18. return s.join("");
  19. }
  20. /**
  21. * 生成OSS签名配置
  22. */
  23. function generateOSSConfig() {
  24. // 设置1小时后过期
  25. let date = new Date()
  26. date = date.setHours(date.getHours() + 1)
  27. let extime = "" + new Date(date).toISOString()
  28. let policyText = {
  29. "expiration": extime,
  30. "conditions": [
  31. ["content-length-range", 0, 1024 * 1024 * 100] // 设置上传文件的大小限制100MB
  32. ]
  33. };
  34. const policyBase64 = Base64.encode(JSON.stringify(policyText))
  35. // 生成签名
  36. let bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, config.aliOSS_secretKey, {
  37. asBytes: true
  38. });
  39. let signature = Crypto.util.bytesToBase64(bytes);
  40. return {
  41. accessid: config.aliOSS_accessKey,
  42. host: `https://${config.aliOSS_bucketName}.${config.endpoint}`,
  43. signature: signature,
  44. policyBase64: policyBase64,
  45. }
  46. }
  47. /**
  48. * OSS上传功能使用签名认证
  49. * @param {Object} file - 文件对象uni.chooseImage返回的文件
  50. * @returns {Promise<Object>} 返回上传结果
  51. */
  52. const uploadImage = async (file) => {
  53. try {
  54. // 生成OSS配置和签名
  55. const ossConfig = generateOSSConfig()
  56. // 生成唯一文件名
  57. const timestamp = Date.now()
  58. const randomStr = Math.random().toString(36).substring(2, 8)
  59. const fileExtension = getFileExtension(file.name || file.path || '.jpg')
  60. const fileName = `avatars/${timestamp}_${randomStr}${fileExtension}`
  61. const result = await uni.uploadFile({
  62. url: ossConfig.host,
  63. filePath: file.path || file.tempFilePath,
  64. name: 'file',
  65. formData: {
  66. key: fileName,
  67. policy: ossConfig.policyBase64,
  68. OSSAccessKeyId: ossConfig.accessid,
  69. success_action_status: '200',
  70. signature: ossConfig.signature,
  71. }
  72. })
  73. console.log('OSS上传结果:', result)
  74. // 检查上传是否成功
  75. if (result.errMsg && result.errMsg.includes("uploadFile:ok")) {
  76. const fileUrl = `${config.staticDomain}${fileName}`
  77. return {
  78. success: true,
  79. url: fileUrl,
  80. fileName: fileName
  81. }
  82. } else {
  83. throw new Error(`OSS上传失败,状态码: ${result.statusCode}, 错误信息: ${result.errMsg}`)
  84. }
  85. } catch (error) {
  86. console.error('OSS上传失败:', error)
  87. return {
  88. success: false,
  89. error: error.message || 'OSS上传失败'
  90. }
  91. }
  92. }
  93. /**
  94. * 获取文件扩展名
  95. */
  96. const getFileExtension = (fileName) => {
  97. if (!fileName) return '.jpg'
  98. const lastDot = fileName.lastIndexOf('.')
  99. return lastDot !== -1 ? fileName.substring(lastDot) : '.jpg'
  100. }
  101. /**
  102. * 选择并上传图片到OSS一步到位
  103. */
  104. const chooseAndUpload = async () => {
  105. try {
  106. // 选择图片
  107. const chooseResult = await uni.chooseImage({
  108. count: 1,
  109. sizeType: ['compressed'],
  110. sourceType: ['album', 'camera']
  111. })
  112. if (chooseResult.tempFilePaths && chooseResult.tempFilePaths.length > 0) {
  113. const file = {
  114. path: chooseResult.tempFilePaths[0],
  115. tempFilePath: chooseResult.tempFilePaths[0]
  116. }
  117. // 显示加载提示
  118. uni.showLoading({ title: '上传到OSS中...' })
  119. // 上传文件到OSS
  120. const uploadResult = await uploadImage(file)
  121. uni.hideLoading()
  122. if (uploadResult.success) {
  123. uni.showToast({ title: 'OSS上传成功', icon: 'success' })
  124. return uploadResult
  125. } else {
  126. uni.showToast({ title: uploadResult.error, icon: 'error' })
  127. return null
  128. }
  129. }
  130. } catch (error) {
  131. uni.hideLoading()
  132. uni.showToast({ title: 'OSS上传失败', icon: 'error' })
  133. console.error('OSS上传失败:', error)
  134. return null
  135. }
  136. }
  137. export {
  138. uploadImage,
  139. chooseAndUpload,
  140. getFileExtension
  141. }