Golang gin框架阿里云OSS上传多种情况实战

文档地址:

https://help.aliyun.com/document_detail/32144.html?spm=a2c4g.11174283.6.1085.55aa7da2CpaepD

安装SDK
执行以下命令安装OSS Go SDK:

go get github.com/aliyun/aliyun-oss-go-sdk/oss

运行以下代码查看OSS Go SDK版本:

package main

import (
  "fmt"
  "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
  fmt.Println("OSS Go SDK Version: ", oss.Version)
}

封装方法:

核心文件:


func (this *Config) OssCennect() (Bucket *oss.Bucket, err error) {
//此处需要进入阿里云oss控制台配置域名
	this.Endpoint = "https://image.xxxxxxx.com"
	this.AccessKeyId = "你的accessKeyId"
	this.AccessKeySecret = "你的Secret"
	this.Region = "选区:我的oss-cn-beijing"
	this.Bucket = "bucket名称"
	this.Secure = true
	this.Cname = true
	client, err := oss.New(this.Endpoint, this.AccessKeyId, this.AccessKeySecret, oss.UseCname(true))
	if err != nil {
		fmt.Println(err)
	}
	Bucket, err = client.Bucket("tybk")

	return

}

1.文件流直传阿里云oss不存服务器:

func (this *Config) LocalUrl(file io.Reader) (url string, err error) {
	Bucket, err := this.OssCennect()
	if err != nil {
		panic(err)
	}

	t := time.Now()
	fmt.Println(t.Year())
	//拼接文件名称
	fileName := fmt.Sprintf("%s%s%s%s%s%s%s", strconv.Itoa(t.Year()), strconv.Itoa(int(t.Month())), strconv.Itoa(t.Day()), strconv.Itoa(t.Hour()), strconv.Itoa(t.Minute()), strconv.Itoa(t.Second()), strconv.Itoa(int(t.Unix())))
	fmt.Println("...s......................")
	fmt.Println(fileName)
	str := "test/" + fileName + ".jpg"

	err = Bucket.PutObject(str, file)
	if err != nil {
		url = "上传错误"
	} else {
		url = fmt.Sprintf("%s%s", "https://static.xxxxxxxi.cn/", str)
	}
	return url, err

}

2.通过url图片地址直存oss

func (this *Config) HttpUrl(uri string) (urlb string, err error) {
//获得文件流
	res, err := http.Get(uri)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	Bucket, err := this.OssCennect()
	if err != nil {
		panic(err)
	}
	fmt.Println("------------name--------------")

	t := time.Now()
	fmt.Println(t.Year())
	fileName := fmt.Sprintf("%s%s%s%s%s%s%s", strconv.Itoa(t.Year()), strconv.Itoa(int(t.Month())), strconv.Itoa(t.Day()), strconv.Itoa(t.Hour()), strconv.Itoa(t.Minute()), strconv.Itoa(t.Second()), strconv.Itoa(int(t.Unix())))
	fmt.Println("...s......................")
	fmt.Println(fileName)
	str := "user/" + fileName + ".jpg"
	err = Bucket.PutObject(str, res.Body)
	if err != nil {
		urlb = "上传错误"
	} else {
		urlb = fmt.Sprintf("%s%s", "https://static.txxxxxxx.cn/", str)
	}
	//"https://static.tianyuanzhuyi.cn" +

	return urlb, err
}

3.调用示例(1)

url直传阿里云oss
如下报文
在这里插入图片描述

调用示例(2)

前端文件流直传阿里云oss
报文:
在这里插入图片描述
需要完整代码请下方留言
完整代码地址:

https://download.csdn.net/download/weixin_43273113/14121771

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43273113/article/details/112511607