GO OSS 前端直传 Presign
go 服务端代码
官方文档
阿里云直传
参考代码
注意事项:
- header不需要传
- &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>