天天看點

寫一個分片上傳的demo

作者:也許頹廢也

Minio是一種開源的對象存儲伺服器,支援分布式部署和高可用性。Minio支援分片上傳,即将一個大檔案分成多個小塊進行上傳,可以提高上傳效率和可靠性,也可以避免一次上傳過程中出現網絡中斷或其他異常情況導緻上傳失敗。 以下是使用golang語言編寫minio分片上傳的簡單示例代碼::

package main
import (
    "fmt"
    "github.com/minio/minio-go/v7"
    "github.com/minio/minio-go/v7/pkg/credentials"
    "os"
)
func main() {
    // 初始化一個Minio用戶端對象
    endpoint := "play.min.io"
    accessKeyID := "Q3AM3UQ867SPQQA43P2F"
    secretAccessKey := "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"
    // 使用SSL加密連接配接
    useSSL := true
    minioClient, err := minio.New(endpoint, &minio.Options{
        Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
        Secure: useSSL,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    // 開始一個分片上傳任務
    bucketName := "mybucket"
    objectName := "myobject"
    uploadID, err := minioClient.NewMultipartUpload(context.Background(), bucketName, objectName, minio.PutObjectOptions{})
    if err != nil {
        fmt.Println(err)
        return
    }
    // 将檔案分成多個小塊,并上傳到Minio伺服器
    partSize := int64(10 * 1024 * 1024) // 每個小塊的大小為10MB
    file, err := os.Open("largefile")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer file.Close()
    fileInfo, _ := file.Stat()
    fileSize := fileInfo.Size()
    totalPartsCount := uint32(fileSize / partSize)
    var parts []minio.PartInfo
    var uploadedParts []minio.CompletePart
    for i := uint32(1); i <= totalPartsCount+1; i++ {
        partSize64 := int64(partSize)
        if i == totalPartsCount+1 {
            partSize64 = fileSize % partSize
        }
        part, err := minioClient.PutObjectPart(context.Background(), bucketName, objectName, uploadID, i, file, partSize64, minio.PutObjectPartOptions{})
        if err != nil {
            fmt.Println(err)
            return
        }
        parts = append(parts, part)
        uploadedParts = append(uploadedParts, minio.CompletePart{
            PartNumber: int(i),
            ETag:       part.ETag,
        })
    }
    // 完成分片上傳任務
    _, err = minioClient.CompleteMultipartUpload(context.Background(), bucketName, objectName, uploadID, uploadedParts, minio.CompleteMultipartUploadOptions{})
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("File uploaded successfully")
}           

繼續閱讀