美文网首页
上传文件到aws3

上传文件到aws3

作者: DifferentMan | 来源:发表于2018-11-19 13:55 被阅读0次
    type S3Handler struct {
        Service *s3.S3
    }
    
    //上传文件到aws3
    func AwsS3() *S3Handler {
        //  配置成使用Minio Server。
        S3Config := &aws.Config{
            Credentials:      credentials.NewStaticCredentials(config.YmxConfig.Ymx3.Ymx_a_k_id, config.YmxConfig.Ymx3.Ymx_s_a_key, ""),
            Endpoint:         aws.String(config.YmxConfig.Ymx3.S3_host),
            Region:           aws.String(config.YmxConfig.Ymx3.S3_region),
            DisableSSL:       aws.Bool(true),
            S3ForcePathStyle: aws.Bool(true),
        }
        // Create a single AWS session (we can re use this if we're uploading many files)
        newSession := session.New(S3Config)
        s3Client := s3.New(newSession)
        handler := S3Handler{
            Service: s3Client,
        }
        return &handler
    }
    
    //上传文件
    func (handler *S3Handler) AddFileToS3(ctx context.Context, bucket string, fileDir string) (err error) {
        // Open the file for use
        file, err := os.Open(fileDir)
        if err != nil {
            return err
        }
        defer file.Close()
    
        // Get file size and read the file content into a buffer
        fileInfo, _ := file.Stat()
        var size int64 = fileInfo.Size()
        buffer := make([]byte, size)
        file.Read(buffer)
    
        // 上传一个新的文件到存储桶
        _, err = handler.Service.PutObject(&s3.PutObjectInput{
            Body:   bytes.NewReader(buffer),
            Bucket: aws.String(bucket),
            Key:    aws.String(fileDir),
        })
        if err != nil {
            log.Fatal(err)
            return err
        }
        return
    }
    

    相关文章

      网友评论

          本文标题:上传文件到aws3

          本文链接:https://www.haomeiwen.com/subject/veoofqtx.html