• 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请求格式

  • 相关阅读:
    麦子学院
    iOS开发系列--地图与定位
    iOS开发多线程篇—线程间的通信
    iOS开发多线程篇—创建线程
    iOS开发多线程篇—多线程简单介绍
    iOS开发网络篇—NSURLConnection基本使用
    iOS开发网络篇—GET请求和POST请求
    iOS开发网络篇—HTTP协议
    用CocoaPods做iOS程序的依赖管理
    新手不了解Xcode和mac系统可能犯得错误和我的建议
  • 原文地址:https://www.cnblogs.com/sumafan/p/11457286.html
Copyright © 2020-2023  润新知