国外MOSE官网
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.

115 lines
3.0 KiB

  1. import config from '@/config'
  2. /**
  3. * OSS直传上传功能无需后端接口
  4. * @param {Object} file - 文件对象uni.chooseImage返回的文件
  5. * @returns {Promise<Object>} 返回上传结果
  6. */
  7. const uploadImage = async (file) => {
  8. try {
  9. // 使用项目配置中的OSS信息
  10. const ossConfig = {
  11. accessKey: config.aliOSS_accessKey,
  12. secretKey: config.aliOSS_secretKey,
  13. bucket: config.aliOSS_bucketName,
  14. endpoint: config.endpoint,
  15. staticDomain: config.staticDomain
  16. }
  17. // 生成唯一文件名
  18. const timestamp = Date.now()
  19. const randomStr = Math.random().toString(36).substring(2, 8)
  20. const fileExtension = getFileExtension(file.name || file.path || '.jpg')
  21. const fileName = `avatars/${timestamp}_${randomStr}${fileExtension}`
  22. // 使用公共读写bucket方案(无需签名)
  23. const uploadUrl = `https://${ossConfig.bucket}.${ossConfig.endpoint}`
  24. const result = await uni.uploadFile({
  25. url: uploadUrl,
  26. filePath: file.path || file.tempFilePath,
  27. name: 'file',
  28. formData: {
  29. 'key': fileName
  30. }
  31. })
  32. console.log('OSS上传结果:', result)
  33. // OSS上传成功的状态码通常是204
  34. if (result.statusCode === 204 || result.statusCode === 200) {
  35. const fileUrl = `${ossConfig.staticDomain}${fileName}`
  36. return {
  37. success: true,
  38. url: fileUrl,
  39. fileName: fileName
  40. }
  41. } else {
  42. throw new Error(`OSS上传失败,状态码: ${result.statusCode}`)
  43. }
  44. } catch (error) {
  45. console.error('OSS上传失败:', error)
  46. return {
  47. success: false,
  48. error: error.message || 'OSS上传失败'
  49. }
  50. }
  51. }
  52. /**
  53. * 获取文件扩展名
  54. */
  55. const getFileExtension = (fileName) => {
  56. if (!fileName) return '.jpg'
  57. const lastDot = fileName.lastIndexOf('.')
  58. return lastDot !== -1 ? fileName.substring(lastDot) : '.jpg'
  59. }
  60. /**
  61. * 选择并上传图片到OSS一步到位
  62. */
  63. const chooseAndUpload = async () => {
  64. try {
  65. // 选择图片
  66. const chooseResult = await uni.chooseImage({
  67. count: 1,
  68. sizeType: ['compressed'],
  69. sourceType: ['album', 'camera']
  70. })
  71. if (chooseResult.tempFilePaths && chooseResult.tempFilePaths.length > 0) {
  72. const file = {
  73. path: chooseResult.tempFilePaths[0],
  74. tempFilePath: chooseResult.tempFilePaths[0]
  75. }
  76. // 显示加载提示
  77. uni.showLoading({ title: '上传到OSS中...' })
  78. // 上传文件到OSS
  79. const uploadResult = await uploadImage(file)
  80. uni.hideLoading()
  81. if (uploadResult.success) {
  82. uni.showToast({ title: 'OSS上传成功', icon: 'success' })
  83. return uploadResult
  84. } else {
  85. uni.showToast({ title: uploadResult.error, icon: 'error' })
  86. return null
  87. }
  88. }
  89. } catch (error) {
  90. uni.hideLoading()
  91. uni.showToast({ title: 'OSS上传失败', icon: 'error' })
  92. console.error('OSS上传失败:', error)
  93. return null
  94. }
  95. }
  96. export {
  97. uploadImage,
  98. chooseAndUpload,
  99. getFileExtension
  100. }