Codex Assistant
2025-11-06 308d3b3b7883a92a761dfaf4f607a9f4658213cf
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import axios from 'axios'
import { serverUrl } from './appConfig.js'
 
 
 
// GraphQL查询获取上传凭证
 
const GET_UPLOAD_CREDENTIALS = `
 
  query GetUploadCredentials {
 
    getUploadCredentials {
 
      bucket
 
      region
 
      key
 
      presignedUrl
 
      expiration
 
    }
 
  }
 
`
 
 
 
// 从后端GraphQL获取上传凭证
 
const getUploadCredentials = async () => {
 
  try {
 
    const response = await axios.post(`${serverUrl}/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 {
 
    // 获取上传凭证
 
    const credentials = await getUploadCredentials()
 
    
 
    // 使用预签名URL
 
    const uploadUrl = credentials.presignedUrl
 
    
 
    // 使用预签名URL上传文件
 
    const uploadResponse = await axios.put(uploadUrl, file, {
 
      headers: {
 
        'Content-Type': file.type,
 
      }
 
    })
 
    
 
    if (uploadResponse.status === 200) {
 
      // 返回文件的访问URL(去掉查询参数)
 
      const fileUrl = `https://${credentials.bucket}.cos.${credentials.region}.myqcloud.com/${credentials.key}`
 
      return fileUrl
 
    } else {
 
      throw new Error(`上传失败,状态码: ${uploadResponse.status}`)
 
    }
 
    
 
  } catch (error) {
 
    throw error
 
  }
 
}