lrj
2 天以前 c61d4fe27c97d2ecc907756aa571a4ef14a7b9b6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import axios from 'axios'
 
// GraphQL查询获取上传凭证
const GET_UPLOAD_CREDENTIALS = `
  query GetUploadCredentials {
    getUploadCredentials {
      bucket
      region
      key
      presignedUrl
      expiration
    }
  }
`
 
// 从后端GraphQL获取上传凭证
const getUploadCredentials = async () => {
  try {
    const response = await axios.post('http://localhost:8080/graphql', {
      query: GET_UPLOAD_CREDENTIALS
    })
    
    if (response.data.errors) {
      throw new Error(response.data.errors[0].message)
    }
    
    return response.data.data.getUploadCredentials
  } catch (error) {
    console.error('获取上传凭证失败:', error)
    throw error
  }
}
 
/**
 * 使用预签名URL上传文件到腾讯云COS
 * @param file 要上传的文件
 * @returns Promise<string> 返回文件的访问URL
 */
export const uploadToCOS = async (file: File): Promise<string> => {
  try {
    console.log('开始获取上传凭证...')
    
    // 获取上传凭证
    const credentials = await getUploadCredentials()
    console.log('获取到上传凭证:', credentials)
    
    // 使用预签名URL
    const uploadUrl = credentials.presignedUrl
    
    console.log('开始上传文件到:', uploadUrl)
    
    // 使用预签名URL上传文件
    const uploadResponse = await axios.put(uploadUrl, file, {
      headers: {
        'Content-Type': file.type,
      }
    })
    
    if (uploadResponse.status === 200) {
      console.log('文件上传成功!')
      // 返回文件的访问URL(去掉查询参数)
      const fileUrl = `https://${credentials.bucket}.cos.${credentials.region}.myqcloud.com/${credentials.key}`
      return fileUrl
    } else {
      throw new Error(`上传失败,状态码: ${uploadResponse.status}`)
    }
    
  } catch (error) {
    console.error('上传文件失败:', error)
    throw error
  }
}