GO OSS 前端直传 Presign

[复制链接]
发表于 2025-12-2 00:47:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
go 服务端代码 

官方文档
阿里云直传
参考代码
留意事项:


  • header不须要传
  • &oss.PutObjectRequest 不要写成 &oss.GetObjectRequest
handler

  1. package handler
  2. import (
  3.         "goshop-api/oss-web/utils"
  4.         "net/http"
  5.         "github.com/gin-gonic/gin"
  6. )
  7. func Presign(ctx *gin.Context) {
  8.         fileName := ctx.Query("fileName")
  9.         if fileName == "" {
  10.                 ctx.JSON(http.StatusBadRequest, gin.H{
  11.                         "error": "fileName is required",
  12.                 })
  13.                 return
  14.         }
  15.         result := utils.GetAliyunOSS().Presign(fileName)
  16.         ctx.JSON(http.StatusOK, gin.H{
  17.                 "url": result.URL,
  18.         })
  19. }
复制代码
utils

  1. package utils
  2. import (
  3.         "context"
  4.         "goshop-api/oss-web/global"
  5.         "time"
  6.         "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
  7.         "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
  8.         "go.uber.org/zap"
  9. )
  10. type AliyunOSS struct {
  11.         Client     *oss.Client
  12.         BucketName string
  13.         Region     string
  14. }
  15. func GetAliyunOSS() *AliyunOSS {
  16.         provider := credentials.NewStaticCredentialsProvider(global.ServerConfig.OssInfo.ApiKey, global.ServerConfig.OssInfo.ApiSecret)
  17.         config := oss.LoadDefaultConfig().
  18.                 WithCredentialsProvider(provider).
  19.                 WithEndpoint(global.ServerConfig.OssInfo.EndPoint).
  20.                 WithRegion(global.ServerConfig.OssInfo.Region).
  21.                 WithSignatureVersion(oss.SignatureVersionV4)
  22.         return &AliyunOSS{
  23.                 Client:     oss.NewClient(config),
  24.                 BucketName: global.ServerConfig.OssInfo.BucketName,
  25.                 Region:     global.ServerConfig.OssInfo.Region,
  26.         }
  27. }
  28. func (o *AliyunOSS) Presign(fileName string) *oss.PresignResult {
  29.         result, err := o.Client.Presign(context.TODO(), &oss.PutObjectRequest{
  30.                 Bucket: oss.Ptr(o.BucketName),
  31.                 Key:    oss.Ptr(fileName),
  32.         },
  33.                 oss.PresignExpires(10*time.Minute),
  34.         )
  35.         if err != nil {
  36.                 panic(err)
  37.         }
  38.         return result
  39. }
复制代码
前端代码

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Test</title>
  7. </head>
  8. <body>
  9.     <button id="btn">点击</button>
  10. </body>
  11. <script>
  12.    
  13.     document.getElementById("btn").addEventListener("click", () => {
  14.         const input = document.createElement("input");
  15.         input.type = "file";
  16.         input.accept = "image/*";
  17.         input.multiple = false;
  18.         input.addEventListener("change", (evt) => {
  19.             const file = evt.target.files[0];
  20.             if (!file) return;
  21.             console.log("file", file);
  22.             const fileReader = new FileReader();
  23.             fileReader.readAsArrayBuffer(file);
  24.             fileReader.addEventListener("load", (e) => {
  25.                 const result = e.target.result;
  26.                 let blob = null;
  27.                 if (typeof result === 'object') {
  28.                     blob = new Blob([result]);
  29.                 } else {
  30.                     blob = result;
  31.                 }
  32.                 fetch("http://localhost:8082/oss/v1/oss/preSign?fileName=demo/example.png", { method: "GET", }).then((response) => {
  33.                     if (!response.ok) return console.log("resposne1", response);
  34.                     return response.json();
  35.                 }).then(data => {
  36.                     console.log("url", data);
  37.                     // const headers = getUrlParams(data.url)
  38.                     // console.log("headers", headers);
  39.                     fetch(data.url, { method: "PUT", body: blob })
  40.                         .then(res => {
  41.                             console.log("成功!", res);
  42.                         }).catch(err => {
  43.                             console.log("失败", err);
  44.                         })
  45.                 });
  46.             });
  47.         });
  48.         input.click();
  49.     })
  50. </script>
  51. </html>
复制代码

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表