golang gin 上传图片到aws s3

要上传图片到aws s3首先需要 知道 aws 的地区 也就是region ,还需要知道储存桶的名字,其次就是Access key ID和Secret access key

package handler

import (
	"bytes"
	"io/ioutil"
	"log"
	"net/http"

	"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"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gopkg.in/yaml.v2"
)

type conf struct {
	AccessKeyID     string `yaml:"AccessKeyID"`
	SecretAccessKey string `yaml:"SecretAccessKey"`
	S3Region        string `yaml:"S3Region"`
	S3Bucket        string `yaml:"S3Bucket"`
}

func (c *conf) GetConf() *conf {
	yamlFile, err := ioutil.ReadFile("conf/app.yaml")
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
	}

	err = yaml.Unmarshal(yamlFile, c)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}
	return c
}

var config conf

func UploadDocument(c *gin.Context) {

	config.GetConf()
	AccessKeyID := config.AccessKeyID
	SecretAccessKey := config.SecretAccessKey
	S3Region := config.S3Region
	S3Bucket := config.S3Bucket

	logger := c.MustGet("logger").(*zap.SugaredLogger)
	fileHeader, err := c.FormFile("file")
	f, err := fileHeader.Open()
	var size int64 = fileHeader.Size

	buffer := make([]byte, size)
	f.Read(buffer)

	creds := credentials.NewStaticCredentials(AccessKeyID, SecretAccessKey, "")
	s, err := session.NewSession(&aws.Config{
		Region:      aws.String(S3Region),
		Credentials: creds,
	})
	if err != nil {
		logger.Errorw("An error occurs when processing file uploading", "error", err)
	}

	_, err = s3.New(s).PutObject(&s3.PutObjectInput{
		Bucket:             aws.String(S3Bucket),
		Key:                aws.String("myfolder" + "/" + fileHeader.Filename),
		ACL:                aws.String("private"),
		Body:               bytes.NewReader(buffer),
		ContentLength:      aws.Int64(size),
		ContentType:        aws.String(http.DetectContentType(buffer)),
		ContentDisposition: aws.String("attachment"),
	})
	if err != nil {
		logger.Errorw("An error occurs when processing file uploading", "error", err)
	}
}

  

上面是postman请求格式

posted @ 2019-09-04 10:06  小酥肉是我  阅读(1216)  评论(0编辑  收藏  举报