当前位置:网站首页>aws s3上传文件
aws s3上传文件
2022-08-02 02:34:00 【Asimov__】
go get github.com/aws/aws-sdk-go
package main
import (
"bytes"
"fmt"
"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"
"io/ioutil"
"log"
"net/http"
"os"
)
func Read(filepath string) []byte {
f, err := os.Open(filepath)
if err != nil {
log.Println("read file fail", err)
return nil
}
defer f.Close()
fd, err := ioutil.ReadAll(f)
if err != nil {
log.Println("read to fd fail", err)
return nil
}
return fd
}
func UploadFileToS3(s *session.Session, raw []byte, filename string) (string, error) {
tempFileName := "cards/" + filename
_, err := s3.New(s).PutObject(&s3.PutObjectInput{
Bucket: aws.String("bucket名称"), // bucket名称
Key: aws.String(tempFileName),
Body: bytes.NewReader(raw),
ContentType: aws.String(http.DetectContentType(raw)),
})
if err != nil {
log.Println("PUT err", err)
return "", err
}
fileUrl := "https://bucket名称.s3.ap-east-1.amazonaws.com/" + tempFileName
return fileUrl, err
}
func main() {
s, err := session.NewSession(&aws.Config{
Region: aws.String("ap-east-1"), // 替换自己账户的region
Credentials: credentials.NewStaticCredentials(
"AccessKeyID",
"SecretAccessKey",
"SessionToken"), // Sessiontoken是进程相关,应该是连接中可以返回 (可为空)
})
if err != nil {
log.Println("aws failed", err)
}
for i := 0; i < 10000; i++ {
f1 := fmt.Sprintf("green_%d.gif", i)
res := Read("./green/" + f1)
fileName, err1 := UploadFileToS3(s, res, f1)
if err1 != nil {
//log.Println("Upload failed ", err1)
} else {
log.Println("upload success ", fileName)
}
}
}
AccessKeyID SecretAccessKey: 在账户(或IAM中建个用户)的security_credentials中申请
边栏推荐
猜你喜欢
51. 数字排列
【Unity入门计划】2D Game Kit:初步了解2D游戏组成
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
ApiFox 基本使用教程(浅尝辄止,非广)
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
网络层解析——IP协议、地址管理、路由选择
国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现
Win Go development kit installation configuration, GoLand configuration
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
记一次gorm事务及调试解决mysql死锁
随机推荐
leetcode/字符串中的变位词-s1字符串的某个排列是s2的子串
OC和Swift语言的区别
Oracle数据类型介绍
内卷的正确打开方式
NIO‘s Sword(牛客多校赛)
Use DBeaver for mysql data backup and recovery
数仓:数仓从ETL到ELT架构的转化以及俩者的区别
最大层内元素和
十字光标太小怎么调节、CAD梦想画图算量技巧
2022 NPDP take an examination of how the results?How to query?
2022-08-01 Reflection
ofstream,ifstream,fstream read and write files
A good book for newcomers to the workplace
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
Service discovery of kubernetes
搭建zabbix监控及邮件报警(超详细教学)
【web】Understanding Cookie and Session Mechanism
AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
记一次gorm事务及调试解决mysql死锁
Pinduoduo leverages the consumer expo to promote the upgrading of domestic agricultural products brands and keep pace with international high-quality agricultural products