v2-s.jpg
go get:

go get github.com/globalsign/mgo/bson
go get github.com/aws/aws-sdk-go

code:

package main

import (
    "bytes"
    "fmt"
    "log"
    "mime/multipart"
    "net/http"
    "path/filepath"

    "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/globalsign/mgo/bson"
)

// UploadFileToS3 上传
func UploadFileToS3(s *session.Session, file multipart.File, fileHeader *multipart.FileHeader) (string, error) {
    size := fileHeader.Size
    buffer := make([]byte, size)
    file.Read(buffer)

    // 此处文件名称即为相对文件名
    tempFileName := "test/" + bson.NewObjectId().Hex()  +  filepath.Ext(fileHeader.Filename)


    _, err := s3.New(s).PutObject(&s3.PutObjectInput{
        Bucket:               aws.String("tttttttttttttt"),  // bucket名称,把自己创建的bucket名称替换到此处即可
        Key:                  aws.String(tempFileName),
        ACL:                  aws.String("public-read"),// 权限枚举 https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl
        Body:                 bytes.NewReader(buffer),
        ContentLength:        aws.Int64(int64(size)),
        ContentType:        aws.String(http.DetectContentType(buffer)),
        ContentDisposition:   aws.String("attachment"),
        ServerSideEncryption: aws.String("AES256"),
        StorageClass:         aws.String("INTELLIGENT_TIERING"),
    })
    if err != nil {
        return "", err
    }
    fileUrl := "https://ttttttttttttttttttttt.s3.ap-east-1.amazonaws.com/" + tempFileName

    return fileUrl, err
}

//  上传图片请求handler
func handler(w http.ResponseWriter, r *http.Request) {
    maxSize := int64(10024000) // 最大10MB

    err := r.ParseMultipartForm(maxSize)
    if err != nil {
        log.Println(err)
        fmt.Fprintf(w, "Image too large. Max Size: %v", maxSize)
        return
    }

    // 文件上传为post请求, formdata file格式
    file, fileHeader, err := r.FormFile("profile_picture")
    if err != nil {
        log.Println(err)
        fmt.Fprintf(w, "Could not get uploaded file")
        return
    }
    defer file.Close()

    // create an AWS session which can be
    // reused if we're uploading many files
    s, err := session.NewSession(&aws.Config{
        Region: aws.String("ap-east-1"),  // 替换自己账户的region
        Credentials: credentials.NewStaticCredentials(
            "ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt", // 替换成自己账户的secret-id
            "tttttttttttttttttttttttttttttttttttttttttttttttttttttttttt ",   // 替换成自己账户的secret-key
            ""),  // token can be left blank for now
    })
    if err != nil {
        fmt.Fprintf(w, "Could not upload file")
    }

    fileName, err := UploadFileToS3(s, file, fileHeader)
    if err != nil {
        fmt.Fprintf(w, "Could not upload file")
    }

    fmt.Fprintf(w, "Image uploaded successfully: %v", fileName)
}

func main() {
    http.HandleFunc("/", handler)
    log.Println("Upload server started")
    log.Fatal(http.ListenAndServe(":80", nil))
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code