当前位置: 首页 > article >正文

GO OSS 前端直传 Presign

go 服务端代码 

官方文档

阿里云直传

参考代码

注意事项:

  1. header不需要传
  2. &oss.PutObjectRequest 不要写成 &oss.GetObjectRequest

handler

package handler

import (
	"goshop-api/oss-web/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Presign(ctx *gin.Context) {
	fileName := ctx.Query("fileName")
	if fileName == "" {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "fileName is required",
		})
		return
	}
	result := utils.GetAliyunOSS().Presign(fileName)

	ctx.JSON(http.StatusOK, gin.H{
		"url": result.URL,
	})
}

utils

package utils

import (
	"context"
	"goshop-api/oss-web/global"
	"time"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
	"go.uber.org/zap"
)

type AliyunOSS struct {
	Client     *oss.Client
	BucketName string
	Region     string
}

func GetAliyunOSS() *AliyunOSS {
	provider := credentials.NewStaticCredentialsProvider(global.ServerConfig.OssInfo.ApiKey, global.ServerConfig.OssInfo.ApiSecret)
	config := oss.LoadDefaultConfig().
		WithCredentialsProvider(provider).
		WithEndpoint(global.ServerConfig.OssInfo.EndPoint).
		WithRegion(global.ServerConfig.OssInfo.Region).
		WithSignatureVersion(oss.SignatureVersionV4)

	return &AliyunOSS{
		Client:     oss.NewClient(config),
		BucketName: global.ServerConfig.OssInfo.BucketName,
		Region:     global.ServerConfig.OssInfo.Region,
	}
}

func (o *AliyunOSS) Presign(fileName string) *oss.PresignResult {
	result, err := o.Client.Presign(context.TODO(), &oss.PutObjectRequest{
		Bucket: oss.Ptr(o.BucketName),
		Key:    oss.Ptr(fileName),
	},
		oss.PresignExpires(10*time.Minute),
	)
	if err != nil {
		panic(err)
	}
	return result
}

前端代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>

<body>

    <button id="btn">点击</button>
</body>
<script>
    
    document.getElementById("btn").addEventListener("click", () => {
        const input = document.createElement("input");
        input.type = "file";
        input.accept = "image/*";
        input.multiple = false;
        input.addEventListener("change", (evt) => {
            const file = evt.target.files[0];
            if (!file) return;
            console.log("file", file);
            const fileReader = new FileReader();
            fileReader.readAsArrayBuffer(file);
            fileReader.addEventListener("load", (e) => {
                const result = e.target.result;
                let blob = null;
                if (typeof result === 'object') {
                    blob = new Blob([result]);
                } else {
                    blob = result;
                }
                fetch("http://localhost:8082/oss/v1/oss/preSign?fileName=demo/example.png", { method: "GET", }).then((response) => {
                    if (!response.ok) return console.log("resposne1", response);
                    return response.json();
                }).then(data => {
                    console.log("url", data);
                    // const headers = getUrlParams(data.url)
                    // console.log("headers", headers);
                    fetch(data.url, { method: "PUT", body: blob })
                        .then(res => {
                            console.log("成功!", res);
                        }).catch(err => {
                            console.log("失败", err);
                        })
                });
            });
        });
        input.click();
    })
</script>

</html>


http://www.kler.cn/a/444391.html

相关文章:

  • 快速解决oracle 11g中exp无法导出空表的问题
  • InnoDB 查询成本
  • 【Leetcode Top 100】105. 从前序与中序遍历序列构造二叉树
  • Python:动态粒子爱心
  • Spring IOC 和 AOP的学习笔记
  • Spring篇--xml方式整合第三方框架
  • linux CentOS系统上卸载docker
  • Android Binder 进程间通信
  • 肝了半年,我整理出了这篇云计算学习路线(新手必备,从入门到精通)
  • Diffusino Policy学习note
  • Unbuntu下怎么生成SSL自签证书?
  • 聊聊开源的虚拟化平台--PVE
  • 02、10个富士胶片模拟的设置
  • 使用 Canal 监听 MySQL Binlog 日志实现最终一致性
  • 《算法SM3》题目
  • 零基础开始学习鸿蒙开发-交友软件页面设计
  • 【开源免费】基于Vue和SpringBoot的靓车汽车销售网站(附论文)
  • 系统移植——Linux 内核顶层 Makefile 详解
  • 谈谈网络流量控制
  • python学opencv|读取图像(十六)修改HSV图像HSV值