1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| package main
import ( "bytes" "context" "fmt" "io" "os"
"github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" )
func main() { endpoint := "play.min.io" accessKeyID := "YOUR-ACCESSKEYID" secretAccessKey := "YOUR-SECRETACCESSKEY" bucketName := "my-bucketname" objectName := "my-objectname" filePath := "path/to/largefile"
minioClient, err := minio.New(endpoint, &minio.Options{ Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), Secure: true, }) if err != nil { fmt.Println(err) return }
err = multipartUpload(minioClient, bucketName, objectName, filePath) if err != nil { fmt.Println(err) } }
func multipartUpload(minioClient *minio.Client, bucketName, objectName, filePath string) error { ctx := context.Background()
uploadID, err := minioClient.NewMultipartUpload(ctx, bucketName, objectName, minio.PutObjectOptions{}) if err != nil { return fmt.Errorf("failed to initiate multipart upload: %w", err) }
file, err := os.Open(filePath) if err != nil { return fmt.Errorf("failed to open file: %w", err) } defer file.Close()
var parts []minio.CompletePart partSize := int64(5 * 1024 * 1024) buffer := make([]byte, partSize) partNumber := 1
for { bytesRead, err := file.Read(buffer) if err != nil && err != io.EOF { return fmt.Errorf("failed to read file: %w", err) } if bytesRead == 0 { break }
part, err := minioClient.PutObjectPart(ctx, bucketName, objectName, uploadID, partNumber, bytes.NewReader(buffer[:bytesRead]), partSize, minio.PutObjectPartOptions{}) if err != nil { return fmt.Errorf("failed to upload part %d: %w", partNumber, err) } parts = append(parts, minio.CompletePart{ PartNumber: partNumber, ETag: part.ETag, }) partNumber++ }
_, err = minioClient.CompleteMultipartUpload(ctx, bucketName, objectName, uploadID, parts) if err != nil { return fmt.Errorf("failed to complete multipart upload: %w", err) }
fmt.Println("Multipart upload completed.") return nil }
|