Web 直接上传 S3 技术方案验证 | Golang 实现

将线上传文件到 AWS S3 的方案中,最常用的是前端直接上传,后端生成签名,然后前端通过签名上传到 AWS S3。

AWS S3 一次性签名上传方案(Golang实现)

下面是一个完整的AWS S3一次性签名上传方案实现,包含后端Golang代码和前端示例。

系统架构

  1. 前端请求后端获取一次性签名
  2. 后端生成一次性使用的预签名URL
  3. 前端使用该URL直接上传文件到S3
  4. 前端通知后端上传完成
  5. 后端验证文件并存储元数据

后端Golang实现

1. 主要依赖

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// go.mod
module s3-upload-demo

go 1.21

require (
    github.com/aws/aws-sdk-go v1.50.0
    github.com/gin-gonic/gin v1.9.1
    github.com/google/uuid v1.6.0
)

2. 核心代码

  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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// main.go
package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
    "github.com/gin-gonic/gin"
    "github.com/google/uuid"
)

// 配置结构体
type Config struct {
    AWSRegion          string
    AWSAccessKeyID     string
    AWSSecretAccessKey string
    S3Bucket           string
    ServerPort         string
}

// 上传元数据
type UploadMetadata struct {
    ID        string    `json:"id"`
    FileName  string    `json:"file_name"`
    FilePath  string    `json:"file_path"`
    FileSize  int64     `json:"file_size"`
    MimeType  string    `json:"mime_type"`
    UploadedAt time.Time `json:"uploaded_at"`
    UserID    string    `json:"user_id"` // 可选:关联用户
}

// 应用主要结构
type App struct {
    Config *Config
    S3     *s3.S3
    Router *gin.Engine
    // 实际应用中应该使用数据库存储元数据
    Uploads map[string]*UploadMetadata
}

// 初始化应用
func NewApp(config *Config) *App {
    // 创建AWS会话
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String(config.AWSRegion),
        Credentials: credentials.NewStaticCredentials(
            config.AWSAccessKeyID,
            config.AWSSecretAccessKey,
            "",
        ),
    })
    if err != nil {
        log.Fatalf("Failed to create AWS session: %v", err)
    }

    // 创建S3服务客户端
    s3Client := s3.New(sess)

    app := &App{
        Config:  config,
        S3:      s3Client,
        Router:  gin.Default(),
        Uploads: make(map[string]*UploadMetadata),
    }

    app.setupRoutes()
    return app
}

// 设置路由
func (app *App) setupRoutes() {
    app.Router.POST("/api/upload/sign", app.generatePresignedURL)
    app.Router.POST("/api/upload/complete", app.completeUpload)
    app.Router.GET("/api/upload/:id", app.getUploadMetadata)
}

// 生成预签名URL请求
type GeneratePresignedURLRequest struct {
    FileName string `json:"file_name" binding:"required"`
    FileType string `json:"file_type" binding:"required"`
}

// 生成预签名URL响应
type GeneratePresignedURLResponse struct {
    UploadID  string `json:"upload_id"`
    URL       string `json:"url"`
    ExpiresAt int64  `json:"expires_at"`
}

// 生成一次性预签名URL
func (app *App) generatePresignedURL(c *gin.Context) {
    var req GeneratePresignedURLRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    // 生成唯一上传ID和文件名
    uploadID := uuid.New().String()
    fileExt := getFileExtension(req.FileName)
    s3Key := fmt.Sprintf("uploads/%s/%s%s", time.Now().Format("2006/01/02"), uploadID, fileExt)

    // 创建预签名PUT请求(一次性使用)
    reqs, _ := app.S3.PutObjectRequest(&s3.PutObjectInput{
        Bucket: aws.String(app.Config.S3Bucket),
        Key:    aws.String(s3Key),
        // 可以添加ContentType和ContentLength限制
    })

    // 生成预签名URL,设置15分钟过期和一次性使用
    url, headers, err := reqs.PresignRequest(15 * time.Minute)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate presigned URL"})
        return
    }

    // 存储上传元数据(实际应用中应使用数据库)
    metadata := &UploadMetadata{
        ID:        uploadID,
        FileName:  req.FileName,
        FilePath:  s3Key,
        UploadedAt: time.Now(),
    }
    app.Uploads[uploadID] = metadata

    // 记录headers用于验证(实际应用中应存储这些信息)
    _ = headers

    c.JSON(http.StatusOK, GeneratePresignedURLResponse{
        UploadID:  uploadID,
        URL:       url,
        ExpiresAt: time.Now().Add(15 * time.Minute).Unix(),
    })
}

// 上传完成请求
type CompleteUploadRequest struct {
    UploadID string `json:"upload_id" binding:"required"`
}

// 上传完成响应
type CompleteUploadResponse struct {
    Success bool   `json:"success"`
    Message string `json:"message"`
    FileURL string `json:"file_url,omitempty"`
}

// 处理上传完成
func (app *App) completeUpload(c *gin.Context) {
    var req CompleteUploadRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    // 获取上传元数据
    metadata, exists := app.Uploads[req.UploadID]
    if !exists {
        c.JSON(http.StatusNotFound, gin.H{"error": "Upload not found"})
        return
    }

    // 验证S3中文件是否存在
    exists, err := app.verifyS3File(metadata.FilePath)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to verify file"})
        return
    }

    if !exists {
        c.JSON(http.StatusBadRequest, gin.H{"error": "File not found in S3"})
        return
    }

    // 获取文件详细信息
    fileInfo, err := app.getS3FileInfo(metadata.FilePath)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get file info"})
        return
    }

    // 更新元数据
    metadata.FileSize = fileInfo.Size
    metadata.MimeType = fileInfo.ContentType
    metadata.UploadedAt = time.Now()

    // 在实际应用中,这里应该将元数据保存到数据库

    c.JSON(http.StatusOK, CompleteUploadResponse{
        Success: true,
        Message: "File uploaded successfully",
        FileURL: fmt.Sprintf("https://%s.s3.%s.amazonaws.com/%s", 
            app.Config.S3Bucket, app.Config.AWSRegion, metadata.FilePath),
    })
}

// S3文件信息
type S3FileInfo struct {
    Size        int64
    ContentType string
    LastModified time.Time
}

// 验证S3中文件是否存在
func (app *App) verifyS3File(key string) (bool, error) {
    _, err := app.S3.HeadObject(&s3.HeadObjectInput{
        Bucket: aws.String(app.Config.S3Bucket),
        Key:    aws.String(key),
    })

    if err != nil {
        return false, err
    }
    return true, nil
}

// 获取S3文件信息
func (app *App) getS3FileInfo(key string) (*S3FileInfo, error) {
    result, err := app.S3.HeadObject(&s3.HeadObjectInput{
        Bucket: aws.String(app.Config.S3Bucket),
        Key:    aws.String(key),
    })

    if err != nil {
        return nil, err
    }

    return &S3FileInfo{
        Size:        *result.ContentLength,
        ContentType: *result.ContentType,
        LastModified: *result.LastModified,
    }, nil
}

// 获取上传元数据
func (app *App) getUploadMetadata(c *gin.Context) {
    uploadID := c.Param("id")
    
    metadata, exists := app.Uploads[uploadID]
    if !exists {
        c.JSON(http.StatusNotFound, gin.H{"error": "Upload not found"})
        return
    }
    
    c.JSON(http.StatusOK, metadata)
}

// 获取文件扩展名
func getFileExtension(filename string) string {
    for i := len(filename) - 1; i >= 0; i-- {
        if filename[i] == '.' {
            return filename[i:]
        }
    }
    return ""
}

// 主函数
func main() {
    config := &Config{
        AWSRegion:          "us-east-1",
        AWSAccessKeyID:     "your-access-key-id",
        AWSSecretAccessKey: "your-secret-access-key",
        S3Bucket:           "your-bucket-name",
        ServerPort:         "8080",
    }

    app := NewApp(config)
    
    log.Printf("Server starting on port %s", config.ServerPort)
    log.Fatal(app.Router.Run(":" + config.ServerPort))
}

前端示例

 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
<!DOCTYPE html>
<html>
<head>
    <title>S3文件上传示例</title>
</head>
<body>
    <h1>文件上传</h1>
    <input type="file" id="fileInput">
    <button onclick="uploadFile()">上传文件</button>
    <div id="status"></div>
    <div id="result"></div>

    <script>
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const statusDiv = document.getElementById('status');
            const resultDiv = document.getElementById('result');
            
            if (!fileInput.files.length) {
                alert('请选择文件');
                return;
            }
            
            const file = fileInput.files[0];
            
            try {
                statusDiv.textContent = '请求上传签名...';
                
                // 1. 从后端获取预签名URL
                const signResponse = await fetch('/api/upload/sign', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        file_name: file.name,
                        file_type: file.type
                    })
                });
                
                if (!signResponse.ok) {
                    throw new Error('获取签名失败');
                }
                
                const signData = await signResponse.json();
                statusDiv.textContent = '上传文件中...';
                
                // 2. 使用预签名URL直接上传到S3
                const uploadResponse = await fetch(signData.url, {
                    method: 'PUT',
                    body: file,
                    headers: {
                        'Content-Type': file.type
                    }
                });
                
                if (!uploadResponse.ok) {
                    throw new Error('上传到S3失败');
                }
                
                statusDiv.textContent = '通知后端上传完成...';
                
                // 3. 通知后端上传完成
                const completeResponse = await fetch('/api/upload/complete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        upload_id: signData.upload_id
                    })
                });
                
                if (!completeResponse.ok) {
                    throw new Error('完成上传通知失败');
                }
                
                const completeData = await completeResponse.json();
                statusDiv.textContent = '上传完成!';
                resultDiv.innerHTML = `
                    <p>文件上传成功</p>
                    <p>文件URL: <a href="${completeData.file_url}" target="_blank">${completeData.file_url}</a></p>
                `;
                
            } catch (error) {
                statusDiv.textContent = '上传失败: ' + error.message;
                console.error('Upload error:', error);
            }
        }
    </script>
</body>
</html>

部署和配置说明

  1. 配置AWS凭证:确保设置正确的AWS访问密钥和S3存储桶名称
  2. CORS配置:在S3存储桶上设置适当的CORS策略以允许前端上传
  3. 安全性
    • 在实际生产环境中添加身份验证
    • 考虑添加文件大小和类型限制
    • 使用数据库存储上传元数据而不是内存

扩展建议

  1. 添加文件大小和类型验证
  2. 实现分块上传支持大文件
  3. 添加用户身份验证和授权
  4. 实现上传进度跟踪
  5. 添加病毒扫描功能
  6. 实现文件处理(如图像压缩、格式转换等)

这个方案提供了安全的一次性签名机制,确保每个签名只能使用一次,并且有过期时间限制,同时后端能够验证上传结果并存储元数据。

参考