zoukankan      html  css  js  c++  java
  • 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请求格式

  • 相关阅读:
    设计模式--总结
    设计模式--行为型模式--解释器模式
    设计模式--行为型模式--备忘录模式
    设计模式--行为型模式--访问者模式(Visitor模式)
    设计模式--行为型模式--迭代器模式
    设计模式--行为型模式--中介者模式
    js常用方法集合
    CSS 每隔4行显示不同样式的表格
    常用正则验证
    wIndow 强制关闭被占用的端口
  • 原文地址:https://www.cnblogs.com/sumafan/p/11457286.html
Copyright © 2011-2022 走看看